简体   繁体   中英

Retrieving XmlNode SelectSingleNode Parents Node

stack overflow has helped me a ton and decided to join and ask a question myself.

My process that I am trying to do is basically select a node out of an XML document and delete the entire node that the user had selected.

Now for some code!

int index = index = list_serverlist.SelectedIndex;
string selectedItem = list_serverlist.Items[index].ToString();

XmlNode selectedNode = doc.SelectSingleNode("/ServerList/Server/ServerName[text()='" + selectedItem + "']");

selectedNode.ParentNode.RemoveAll();
doc.Save(filePath);

Also the XML file that I am using

<?xml version="1.0"?>
<ServerList>
  <Server>
    <ServerName>FAB13-HST01</ServerName>
    <ServerIP>wasd</ServerIP>
    <ServerUsername>..\Administrator</ServerUsername>
    <ServerPassword>wasd</ServerPassword>
  </Server>
  <Server>
    <ServerName>FAB13-HST02</ServerName>
    <ServerIP>wasd</ServerIP>
    <ServerUsername>..\Administrator</ServerUsername>
    <ServerPassword>wasd</ServerPassword>
  </Server>
  <Server>
    <ServerName>FAB13-HST03</ServerName>
    <ServerIP>wasd</ServerIP>
    <ServerUsername>..\Administrator</ServerUsername>
    <ServerPassword>wasd</ServerPassword>
  </Server>
</ServerList>

Now how I see that code happening is...

basically I get what the user selected out of the ListBox make it a string and than select the single node that has that in the ServerName field. Which when debugging seems to work fine.

However when I use the command

selectedNode.ParentNode.RemoveAll();

It deletes all childs of the node, and not including the parent null. When I debug it and try to get the Parent it seems to be returning null for some odd reason and can't figure out why.

New to XML so not sure what I am doing wrong...

If you try to get the parent after calling RemoveAll(), the selected node no longer exists.

To remove the whole server element, you could use something like.

    XmlNode nodeParent = selectedNode.ParentNode;
    nodeParent.ParentNode.RemoveChild(nodeParent);

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