-1

I have xml as under

<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>

I want to delete the nodes and it's subnodes whose serverid="1".

Final output will be

<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>

How can I do so?

4

1 回答 1

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();
于 2013-06-09T13:21:40.203 回答