如何从文件中删除特定的XML标记并将其保存回来
本文关键字:回来 保存 XML 文件 删除 | 更新日期: 2023-09-27 18:08:25
我有下面的XML文件
<?xml version="1.0"?>
<configuration>
<appSettings>
<!--Settings-->
<add key="url" value="http://vmcarekey.com"/>
<add key="user" value="admin"/>
<add key="pass" value="password"/> <!-- Remove this line -->
</appSettings>
</configuration>
我想用c#删除key="pass"的xml标签,并将xml保存在原始文件中。
我想输出如下所示的xml
<?xml version="1.0"?>
<configuration>
<appSettings>
<!--Settings-->
<add key="url" value="http://vmcarekey.com"/>
<add key="user" value="admin"/>
</appSettings>
</configuration>
请指导我实现这一点。
使用LinqToXml很容易做到
var xDoc = XDocument.Load(filename);
xDoc.XPathSelectElement("//appSettings/add[@key='pass']").Remove();
xDoc.Save(filename);
试试这个:
XDocument xdoc = XDocument.Load(filename);
xdoc.Element("configuration").Element("appSettings").Elements("add")
.Where(x => (string)x.Attribute("key") == "pass").Remove();
xdoc.Save(filename);