我有
下的xml<databaseserver>
<server name="server1" serverid="1">
<databases>
<database dbid="1" dbname="db1" />
<database dbid="2" dbname="db2" />
</databases>
</server>
<server name="server2" serverid="2">
<databases>
<database dbid="1" dbname="db1" />
<database dbid="2" dbname="db2" />
</databases>
</server>
<server name="server3" serverid="3">
<databases>
<database dbid="1" dbname="db1" />
<database dbid="2" dbname="db2" />
</databases>
</server>
</databaseserver>
我想删除节点及其serverid =“1”的子节点。
最终输出将是
<databaseserver>
<server name="server2" serverid="2">
<databases>
<database dbid="1" dbname="db1" />
<database dbid="2" dbname="db2" />
</databases>
</server>
<server name="server3" serverid="3">
<databases>
<database dbid="1" dbname="db1" />
<database dbid="2" dbname="db2" />
</databases>
</server>
</databaseserver>
我该怎么办?
答案 0 :(得分:2)
var xDoc = XDocument.Load(filename);
xDoc.Descendants("server")
.First(s => s.Attribute("serverid").Value == "1")
.Remove();
var newXml = xDoc.ToString();
XPath也是可能的
xDoc.XPathSelectElement("//server[@serverid='1']").Remove();