删除具有特定值的子节点

时间:2014-07-21 14:13:22

标签: c# xml xpath

尝试从XPath中删除包含值“dfdfdfd”的列表名称

XmlNode names = LoadDocument(xml).DocumentElement.SelectSingleNode("//Class[@Name='" + getCurClass() + "']/Property[@Id='" + i + "']/Lists[contains(ListName,'ws_Users')]");

执行此声明后:

names.RemoveChild(names.FirstChild); 

但我什么都没发生。

我的XML:

<?xml version="1.0" encoding="utf-8"?>
<Root>
  <Class Name="ECMInstruction" Style="Top">
    <Entity Id="1" Name="DocumentInformation" />
    <Property Id="1">
    </Property>
    <Property Id="2">
      <Lists>
        <ListName>ws_Users</ListName>
         <ListName>dfdfdfd</ListName>
      </Lists>
    </Property>
  </Class>
</Root>

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

您需要将修改后的XmlDocument对象保存回文件:

XmlDocument doc = LoadDocument(xml);
XmlNode names = doc.DocumentElement.SelectSingleNode("//Class[@Name='" + getCurClass() + "']/Property[@Id='" + i + "']/Lists[contains(ListName,'ws_Users')]");
names.RemoveChild(names.FirstChild); 
//save `doc` back to file :
doc.Save("path_to_the_xml_file.xml");

或者这样:

XmlNode names = LoadDocument(xml).DocumentElement.SelectSingleNode("//Class[@Name='" + getCurClass() + "']/Property[@Id='" + i + "']/Lists[contains(ListName,'ws_Users')]");
names.RemoveChild(names.FirstChild); 
//save owner `XmlDocument` back to file :
names.OwnerDocument.Save("path_to_the_xml_file.xml");