2011-04-26 154 views
1

我删除了最后一个措辞不佳的问题,并将其解释为最简单的形式。我试图选择一个根节点,但它回来为空。无法从XmlElement中选择根节点

这里是我的XML

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

这里是我的代码

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"); 

编辑:@Marc把我在正确的轨道上。实际上,将节点添加到XmlDocument使其工作

+1

这看起来对我来说outputNode实际上可能是因为.ChildNodes [1]的孩子节点......值得一试,也许。 – Craig 2011-04-26 17:06:35

回答

1

您已创建新的孤儿节点(即尚未在树中),没有任何后代。这是合理的,您的查询相对于那个孤儿找不到任何东西。

要找到现有节点,看.DocumentElement.SelectSingleNode(...)SelectNodes(...)