c# - 使用 LINQ 从 XML 文件中删除所有节点的问题

标签 c# linq-to-xml

我正在尝试从 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/

相关文章:

c# - 如果我快速连续运行多个 Azure 搜索索引器,是否有办法访问 Azure SDK 中的等待索引器队列?

c# - 如何从控制台应用程序打开 WPF 窗口

c# - C#中如何解析XML文件

c# - XDocument 到字符串 : How to omit encoding in declaration?

C# 从 Internet Explorer 获取代理设置

c# - T4 - TT - 在 TT 文件中使用自定义类

c# - linq to xml检查 key 是否存在?

xml - 使用 XDocument.Load 的多线程

c# - "Emulating"Application.Run 使用 Application.DoEvents

c# - 在 XELement 中搜索一个值