我正在尝试从 XML 文件中删除所有节点。但它也删除了根节点开放标记。使用 C# 和 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>
预期操作:
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<!--Log the error count and error message-->
<root>
</root>
实际操作:已编辑
<?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()
。
关于c# - 使用 LINQ 从 XML 文件中删除所有节点的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8216287/