开发者

Can't select root node from XmlElement

I deleted my last, poorly worded question and boiled it down to the simplest form. I am trying to select a root node, but it's coming back as null.

Here's my XML

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <children>
    <child>Clark</child>
    <child>Bruce</child>
    <child>Peter</child>
  </children>
</root>

And here's my code

XmlDocument input = new XmlDocument();
XmlDocument output = new XmlDocument();

input.Load(@"simple.xml");

XmlNode outputNode = output.CreateNode(XmlNodeType.Element, input.ChildNodes[1].Name, null);

Console.WriteLine(outputNode.SelectSingleNode("root") == null ? "null" : "node found"); 
Console.WriteLine(outputNode.SelectSingleNode("/root") == null ? "null" : "node found"); 
Console.WriteLine(outputNode.SelectSingleNode("//root") == null ? "null" : "node found"); 

//After doing this, /root and //root return the root node
output.AppendChild(node);

Console.WriteLine(outputNode.SelectSingleNode("root") == null 开发者_运维知识库? "null" : "node found"); 
Console.WriteLine(outputNode.SelectSingleNode("/root") == null ? "null" : "node found"); 
Console.WriteLine(outputNode.SelectSingleNode("//root") == null ? "null" : "node found"); 

EDIT: @Marc put me on the right track. Actually adding the node to XmlDocument made it work


You have created a new orphan node (i.e. not yet in the tree), without any descendants. It is reasonable that your queries relative to that orphan don't find anything.

To find existing nodes, look at .DocumentElement, .SelectSingleNode(...) and SelectNodes(...)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜