2011-11-21 90 views
4

我想從XML文件中刪除所有節點。但其移除根節點開放標籤也。採用C#ANF的LINQ從XML文件中刪除所有節點的問題usig LINQ

輸入:

<?xml version="1.0" encoding="utf-8" standalone="no"?> 
<!--Log the error count and error message--> 
<root> 
    <ErrData> 
     <Count>1</Count> 
     <Timestamp>2011-11-21T11:57:12.3539044-05:00</Timestamp> 
    </ErrData> 
    <ErrData>max of 20 ErrData elements</ErrData> 
</root> 

預計OP:

<?xml version="1.0" encoding="utf-8" standalone="no"?> 
<!--Log the error count and error message--> 
<root> 
</root> 

實際OP:EDITED

<?xml version="1.0" encoding="utf-8" standalone="no"?> 
    <!--Log the error count and error message--> 
<root /> 

代碼:

XDocument docs = XDocument.Load(path); 
try 
{     
    docs.Descendants("ErrData").Remove(); 
} 

CODE:

下面是我使用的代碼,這個概念是錯誤計數和時間戳登錄到XML file.Once其達到閾值,郵件將被髮送功能,並刪除所有來自xml的節點。然後,當一個錯誤來時,開始進入到下面的xml文件,

XDocument doc = null; 
XElement el; 
if (!System.IO.File.Exists(path)) 
{ 

    doc = new XDocument(new XDeclaration("1.0", "utf-8", "no")); 
    el = new XElement("root"); 
    //el = new XElement("root"); 
    XComment comment = new XComment("Log the error count and error message"); 
    doc.Add(comment); 
} 
else 
{ 
    doc = XDocument.Load(path); 
} 
XElement p1 = new XElement("ErrData"); 
XElement p1Count = new XElement("Count", eventCount); 
XElement p1Windowsatrt = new XElement("Timestamp", windowStart); 

p1.Add(p1Count); 
p1.Add(p1Windowsatrt); 

if (doc.Root != null) 
{ 
    el = doc.Root; 
    el.Add(p1); 
} 
else 
{ 
    el = new XElement("root"); 
    el.Add(p1); 
} 


try 
{ 
    doc.Add(el);//Line throwing the exeception 

} 
catch (Exception e) 
{ 

} 
finally 
{ 
    doc.Save(path); 
} 
+1

你確定缺少開標籤嗎?它不只是縮寫爲? – neeKo

+0

它是我的錯,它是縮寫的根標記。但問題是,下次使用相同的文件來編寫錯誤時,它會拋出「此操作會創建錯誤結構的文檔」。我從這個錯誤開始,但忽略了收尾和標籤。 – Vani

+0

你可以發佈試圖插入新的'ErrData'元素的代碼(你得到異常的地方)嗎? –

回答

1

使用docs.Root.Nodes().Remove()

1

<root />對於沒有內容(自閉標籤)的標籤是有效的XML。如果您絕對需要開放標籤和結束標籤,則需要將一些內容放入根節點中,如評論或文本。

1

混淆在你的第一句話中:「我試圖從XML文件中刪除所有節點/元素。」哪一個?你想刪除所有節點,還是全部元素?

XML中有五種類型的節點:元素,文本,註釋,處理指令和屬性。如果您可以互換地使用「node」和「element」,就像您在這裏一樣,您將無法使用XML處理任何問題。

你得到了什麼,<root/>,是刪除所有後代節點的代碼的正確輸出:它是一個名爲root的單個元素,沒有內容。

你有什麼期望,

<root> 
</root> 

名爲root一個單一的元素包含含有空格子文本節點,可能是一個換行符。您編寫的代碼將刪除所有後代節點,而不僅僅是後代元素節點,因此它也刪除了該文本節點。

+0

我會花更多時間深入學習LINQ概念。謝謝。 – Vani

+0

這些是XML概念,而不是LINQ概念。如果您使用'XmlDocument'方法來執行此操作,則會遇到同樣的問題。 –