2016-07-22 97 views
-1

爲什麼我不能刪除標籤名稱,並保留它的價值我刪除標記名稱,如果標記名稱即時將刪除沒有子節點爲什麼不能使用LINQ爲xml

這裏是xml文件

<p> 
<li> 
     <BibUnstructured>Some text</BibUnstructured> 
    </li> 
    <li> 
     <BibUnstructured>another text</BibUnstructured> 
    </li> 
</p> 

,這是必須在輸出

<p> 
<li> 
     Some text 
    </li> 
    <li> 
     another text 
    </li> 
</p> 

,這裏是我的代碼截至目前

XElement rootBook = XElement.Load("try.xml"); 
      IEnumerable<XElement> Book = 
       from el in rootBook.Descendants("BibUnstructured").ToList() 
       select el; 
      foreach (XElement el in Book) 
      { 
       if (el.HasElements) 
       { 
        el.ReplaceWith(el.Elements()); 
       } 
       Console.WriteLine(el); 
      } 
      Console.WriteLine(rootBook.ToString()); 

如果我刪除if語句刪除其中的標籤名稱及其含量

+0

BibUnstructured沒有任何子元素,只有innerText屬性。 – jdweng

回答

4

BibUnstructured元素沒有孩子元素,但確實有孩子節點(文本節點,在這種情況下) 。試試這個:

foreach (var book in doc.Descendants("BibUnstructured").ToList()) 
{ 
    if (book.Nodes().Any()) 
    { 
     book.ReplaceWith(book.Nodes()); 
    } 
} 

了工作演示見this fiddle

1

查爾斯已經解釋了爲什麼它不工作,或者你也可以做到這一點。

XElement element = XElement.Load("try.xml"); 

    element.Descendants("li").ToList().ForEach(x=> {    
     var item = x.Element("BibUnstructured"); 

     if(item != null) 
     { 
      x.Add(item.Value);  
      item.Remove(); 
     } 
    }); 

入住這Demo

0

你必須父節點的值設置爲你要刪除的子節點的值。 嘗試以下操作:

XElement rootBook = XElement.Load("try.xml"); 
     IEnumerable<XElement> Book = 
      from el in rootBook.Descendants("BibUnstructured").ToList() 
      select el; 
     foreach (XElement el in Book) 
     { 
      if (!el.HasElements) 
      { 
       XElement parent= el.Parent; 
       string value=el.Value; 
       el.Remove(); 
       parent.Value=value; 
       Console.WriteLine(parent); 
      } 

     } 
     Console.WriteLine(rootBook.ToString()); 

,輸出是:

<li>Some text</li> 
<li>another text</li> 
<p> 
<li>Some text</li> 
<li>another text</li> 
</p>