2012-02-27 172 views
0

我正在尝试搜索XML文件,如果找不到某个依赖项,请将该依赖项添加到<dependencies>的末尾。 我的XML文件是这样的:将childnode添加到xml doc

<config> 
     <settings> 
     ... 
     </settings> 
<dependencies> 
<dependency key="#0" type="Windows" name="Microsoft Windows XP" namepart="false"/> 
    . 
    . 
    . 
<dependancy key="#4" type="Windows" name="Microsoft Windows 7" namepart="false" /> 
</dependencies> 

现在我想通过代码添加5依赖。 (<dependancy key="#5" type="Windows" name="Microsoft Windows NT" namepart="false" />) 我该如何去做这件事。我试过使用XMLElement并将其追加到最后。

回答

0

Xml文档未被排序。 你可以检查特定节点,通常使用关键属性。

XmlDocument doc=new XmlDocument(); 
    doc.LoadXMl(youxmlstring); 
    XmlNode node=doc.SelectSingleNode("//dependancy/@name='Microsoft Windows NT'"); 
    if (node==null) 
    { 
      //no such node 
      //insert new node 
    } 

要计算新键属性值,你可以使用类似这样

//assuming key is currectly ordered 
    int nextKey=doc.SelectNodes("//dependancy").Count;  

看到

http://www.codeproject.com/Articles/9494/Manipulate-XML-data-with-XPath-and-XmlDocument-C