的SelectSingleNode返回null使用XPath的已知良好的XML节点路径 [英] SelectSingleNode returning null for known good xml node path using XPath

查看:155
本文介绍了的SelectSingleNode返回null使用XPath的已知良好的XML节点路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个简单的XML文档。这里显示的序列化的XML是从复杂的POCO对象,其模式我无法控制的一个XmlSerializer的结果。

Consider this simple XML document. The serialized XML shown here is the result of an XmlSerializer from a complex POCO object whose schema I have no control over.

<My_RootNode xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="">
  <id root="2.16.840.1.113883.3.51.1.1.1" extension="someIdentifier" xmlns="urn:hl7-org:v3" /> 
  <creationTime xsi:nil="true" xmlns="urn:hl7-org:v3" />      
</My_RootNode>

的目的是提取的ID节点上的扩展属性的值。在这种情况下,我们使用selectSingleNode方法,并给予一个XPath前pression这样:

The goal is to extract the value of the extension attribute on the id node. In this case, we are using the SelectSingleNode method, and given an XPath expression as such:

XmlNode idNode = myXmlDoc.SelectSingleNode("/My_RootNode/id");
//idNode is evaluated to null at this point in the debugger!
string msgID = idNode.Attributes.GetNamedItem("extension").Value;

问题是,的SelectSingleNode 方法返回null对于给定的XPath前pression。

The problem is that the SelectSingleNode method returns null for the given XPath expression.

问:任何在此XPath查询的正确性观念,或者为什么这个方法调用+ XPath的前pression将返回空值?也许命名空间是问题的一部分?

Question: any ideas on this XPath query's correctness, or why this method call + XPath expression would return a null value? Perhaps the namespaces are part of the problem?

推荐答案

我强烈怀疑问题是与命名空间做。尝试摆脱命名空间,你会被罚款 - 但显然不会在你的真实情况,在那里我会假设该文件是固定的帮助

I strongly suspect the problem is to do with namespaces. Try getting rid of the namespace and you'll be fine - but obviously that won't help in your real case, where I'd assume the document is fixed.

我不记得随便如何指定在XPath前pression命名空间,但我敢肯定,这就是问题所在。

I can't remember offhand how to specify a namespace in an XPath expression, but I'm sure that's the problem.

编辑:好的,我想起了现在该怎么做。这是不是非常令人愉快,但 - 你需要创建一个的XmlNamespaceManager 它。下面是一些示例code与示例文档如下:

Okay, I've remembered how to do it now. It's not terribly pleasant though - you need to create an XmlNamespaceManager for it. Here's some sample code that works with your sample document:

using System;
using System.Xml;

public class Test
{
    static void Main()
    {
        XmlDocument doc = new XmlDocument();
        XmlNamespaceManager namespaces = new XmlNamespaceManager(doc.NameTable);
        namespaces.AddNamespace("ns", "urn:hl7-org:v3");
        doc.Load("test.xml");
        XmlNode idNode = doc.SelectSingleNode("/My_RootNode/ns:id", namespaces);
        string msgID = idNode.Attributes["extension"].Value;
        Console.WriteLine(msgID);
    }
}

这篇关于的SelectSingleNode返回null使用XPath的已知良好的XML节点路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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