我想从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'元素的代码(你得到异常的地方)吗? –