1

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

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks man that seemed to work. weird i thought it would of gotten the parent node first and THAN removed all. Guess not. Thanks though that got me passed a main problem! Helped a ton!
Can you add a vote to the answer? I need the points to commit in another forum. Thenks!
Came back to accept as answer. Thanks again for this. It has been a long while since this problem and I have learned a since this!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.