簡體   English   中英

使用LINQ從XML文件中刪除所有節點的問題

[英]Issue in removing all the nodes from XML file using LINQ

我試圖從XML文件中刪除所有節點。 但它也刪除了根節點打開標簽。使用C#anf 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:已編輯

<?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();
}

碼:

下面是我正在使用的代碼,概念是錯誤計數和時間戳記錄到XML文件。一旦達到閾值,電子郵件將按功能發送並從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);
}

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

<root />是沒有內容的標記的有效XML(自閉標記)。 如果您絕對需要開始和結束標記,則需要在根節點中放置一些內容,如注釋或文本。

困惑在於您的第一句話:“我正在嘗試從XML文件中刪除所有節點/元素。” 哪一個? 要刪除所有節點還是所有元素?

XML中有五種類型的節點:元素,文本,注釋,處理指令和屬性。 如果你可以互換地使用“node”和“element”,就像你在這里一樣,你將無需使用XML。

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

你期待什么,

<root>
</root>

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM