C# 为什么 SelectSingleNode 返回 null?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/809496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why is SelectSingleNode returning null?
提问by Todd Richardson
I'm working with an XML document that contains a structure that looks similar to this:
我正在处理一个 XML 文档,该文档包含与此类似的结构:
<MT>
<Events>
<event id="1">
<field name="blah" value="a_value" type="atype" />
.
.
.
</event>
</Events>
</MT>
I'm currently loading this from a file into an XML document in this fashion:
我目前正在以这种方式将它从文件加载到 XML 文档中:
XmlDocument xdoc = new XmlDocument();
xdoc.Load("somefile.xml"); //Successfully loads btw
However I'm running into a problem and only with this one particular document when I try to run the next line of code:
但是,当我尝试运行下一行代码时,我遇到了一个问题,并且只有这个特定文档:
xdoc.SelectSingleNode("//event[@id='1']"); //This returns a null
Am I on the right track by guessing that this is returning null because of an issue with using an attribute named 'id' or am I missing something in code?
我是否在正确的轨道上猜测这是因为使用名为“id”的属性出现问题而返回 null 或者我在代码中遗漏了什么?
采纳答案by Mikko Rantanen
I cannot replicate this using an XML file
我无法使用 XML 文件复制它
<MT>
<Events>
<event id="1">
<field name="blah" value="a_value" type="atype" />
</event>
</Events>
</MT>
And code
和代码
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\test.xml");
XmlNode node = doc.SelectSingleNode("//event[@id='1']");
This returns a non-null node as expected.
这将按预期返回一个非空节点。
Update
更新
After adding a xmlns="example.org"
to the <MT>
element, I had to configure a namespace manager for the XPath and use the namespace for the event. Couldn't get the default namespace to work for some reason.
加入后xmlns="example.org"
的<MT>
元素,我不得不配置一个命名空间经理为XPath和使用的命名空间的事件。由于某种原因无法让默认命名空间工作。
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");
XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);
manager.AddNamespace("e", "http://example.org");
XmlNode node = doc.SelectSingleNode("//e:event[@id='1']", manager);
One thing confused me when trying to get this to work. Why does XmlNamespaceManager need XmlNameTable from the document if not for finding out what namespaces it contains? As in, why do I need to define the NameTable andthe namespace? I'd appreciate if someone who knows could drop a short comment.
当我试图让它发挥作用时,有一件事让我感到困惑。如果不是为了找出它包含的命名空间,为什么 XmlNamespaceManager 需要文档中的 XmlNameTable?正如,为什么我需要定义 NameTable和命名空间?如果知道的人可以发表简短评论,我将不胜感激。