简体   繁体   中英

delete child node with specific value in xml file

Can anyone explain me why I cannot delete this childnode using this query. It gives me an error saying "An unhandled exception of type 'System.ArgumentException' occurred in System.Xml.dll. Additional information: The node to be removed is not a child of this node."

        XmlDocument xDoc = new XmlDocument();
        xDoc.Load("sample.xml");
        xDoc.RemoveChild(xDoc.SelectSingleNode("//Class[@Name='ECMInstruction']/Property[@Id='2']/Lists[contains(ListName,'ws_Users')]"));
        xDoc.Save("sample.xml");

The xml file:

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

It is because of this

Lists[contains(ListName,'ws_Users')]

your xml contains 2 child nodes named ListName of Lists . the first argument of contains() function should contain just a single item. Change that to:

Lists[ListName[contains(.,'ws_Users')]]

An untested attempt:

XmlDocument xDoc = new XmlDocument();
xDoc.Load("sample.xml");
var parent = xDoc.SelectSingleNode("//Class[@Name='ECMInstruction']/Property[@Id='2']/Lists");
var nodeToRemove = parent.SelectSingleNode("ListName[text() = 'ws_Users')]");
parent.RemoveChild(nodeToRemove);
xDoc.Save("sample.xml");

You need to get parent node of the node to be removed and call .RemoveChild() from that parent node :

XmlDocument xDoc = new XmlDocument();
xDoc.Load("sample.xml");
var nodeTobeRemoved = xDoc.SelectSingleNode("//Class[@Name='ECMInstruction']/Property[@Id='2']/Lists/ListName[contains(.,'ws_Users')]");
nodeTobeRemoved.ParentNode.RemoveChild(nodeTobeRemoved);
xDoc.Save("sample.xml");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM