使用XDocument将新节点附加到现有XML

时间:2013-06-09 13:26:06

标签: c# linq-to-xml

我有

下的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>   
</databaseserver>

如何添加新节点

<server name="" serverid="3">
    <databases>
            <database dbid="" dbname="" />        
    </databases>
   </server>

到现有的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="" serverid="3">
    <databases>
            <database dbid="" dbname="" />        
    </databases>
   </server>  
</databaseserver>

1 个答案:

答案 0 :(得分:2)

xDocprevious question

中的相同
xDoc.Root.Add(new XElement("server", 
                new XAttribute("name","server4"),
                new XAttribute("serverid","4"),
                new XElement("databases", 
                    new XElement("database", 
                        new XAttribute("dbid","db4"), 
                        new XAttribute("dbname","name4")))));