简体   繁体   English

检索XmlNode SelectSingleNode父节点

[英]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. 我尝试的过程基本上是从XML文档中选择一个节点,并删除用户选择的整个节点。

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文件

<?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. 基本上我得到用户从ListBox中选择的内容使它成为一个字符串,而不是在ServerName字段中选择具有该字符串的单个节点。 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. 它删除节点的所有子节点,不包括父节点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. 当我调试它并尝试获取Parent时,由于某些奇怪的原因似乎返回null并且无法弄清楚原因。

New to XML so not sure what I am doing wrong... XML的新手,所以不确定我做错了什么...

If you try to get the parent after calling RemoveAll(), the selected node no longer exists. 如果在调用RemoveAll()后尝试获取父节点,则所选节点不再存在。

To remove the whole server element, you could use something like. 要删除整个服务器元素,您可以使用类似的东西。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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