为什么的SelectSingleNode返回null? [英] Why is SelectSingleNode returning null?

查看:200
本文介绍了为什么的SelectSingleNode返回null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与包含类似于这样结构的XML文档的工作:

I'm working with an XML document that contains a structure that looks similar to this:

<MT>
  <Events>
    <event id="1">
      <field name="blah" value="a_value" type="atype" />
      .
      .
      .
     </event>
   </Events>
 </MT>

我目前正在加载此从文件到XML文档以这种方式:

I'm currently loading this from a file into an XML document in this fashion:

XmlDocument xdoc = new XmlDocument();
xdoc.Load("somefile.xml");  //Successfully loads btw

不过我遇到一个问题,仅这一个特定的文件,当我尝试运行code的下一行:

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 

通过猜测,这是因为一个问题返回null使用名为'ID'属性还是我失去了在code的东西我在正确的轨道上吗?

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?

推荐答案

我不能使用XML文件复制此

I cannot replicate this using an XML file

<MT>
  <Events>
    <event id="1">
      <field name="blah" value="a_value" type="atype" />
     </event>
   </Events>
</MT>

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

更新

添加后的xmlns =example.org&LT; MT&GT; 元素,我不得不配置一个命名空间经理为XPath和使用的名称空间的事件。无法得到默认命名空间出于某种原因。

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.

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

试图得到这个工作时,有一件事我弄糊涂了。为什么需要的XmlNamespaceManager从XmlNameTable文件,如果不是发现什么命名空间包含?正如,为什么我需要定义NameTable 命名空间?我倒是AP preciate如果有人谁知道可能下降一个简短的注释。

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 and the namespace? I'd appreciate if someone who knows could drop a short comment.

这篇关于为什么的SelectSingleNode返回null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆