我想從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);
}
你確定缺少開標籤嗎?它不只是縮寫爲 ? –
neeKo
它是我的錯,它是縮寫的根標記。但問題是,下次使用相同的文件來編寫錯誤時,它會拋出「此操作會創建錯誤結構的文檔」。我從這個錯誤開始,但忽略了收尾和標籤。 – Vani
你可以發佈試圖插入新的'ErrData'元素的代碼(你得到異常的地方)嗎? –