问题描述
我有这个 XML:
<?xml version="1.0"?>
<Document xmlns="urn:somethinghere">
<fapx.001.02>
<Sts>
<StsVal>ACCEPTED</StsVal>
</Sts>
</fapx.001.02>
</Document>
我想选择StsVal"的值,为此我编写了这段代码但出现错误:
I want to select value of "StsVal" and for that I wrote this code but getting error:
代码
Dim doc As XmlDocument = New XmlDocument()
doc.Load("myfile.xml")
Dim response As String = doc.SelectSingleNode("Document/fapx.001.02/Sts/StsVal").InnerText
错误
未将对象引用设置为对象的实例.
编辑
我知道我收到此错误是由于 Null 值,可能是因为我在 SelectSingleNode 函数中给出的路径不正确.这就是为什么我想知道如何根据给定的 XML 给出正确的路径.
I know I am getting this error due to Nulll value probably because the path I have given in SelectSingleNode function is not correct. That's why I want to know how to give correct path based on given XML.
推荐答案
那是因为您的 XML 具有默认命名空间:xmlns="urn:somethinghere"
.这个主题(针对具有默认名称空间的 XML 的 XPath 查询)以前在 SO 中以各种形式被问过很多次.以下是我回答历史中的一些内容:
That's because your XML has default namespace : xmlns="urn:somethinghere"
. This topic (XPath query against XML with default namespace) has been asked so many times previously in various forms here in SO. Here are some from my answer history :
这是使用 XPath 和 XmlDocument
查询命名空间中元素的一种可能方法:
And this is one possible way to query element in namespace using XPath and XmlDocument
:
Dim nsManager As New XmlNamespaceManager(New NameTable())
nsManager.AddNamespace("d", "urn:somethinghere")
Dim doc As XmlDocument = New XmlDocument()
doc.Load("myfile.xml")
Dim response As String = doc.SelectSingleNode("d:Document/d:fapx.001.02/d:Sts/d:StsVal", nsManager).InnerText
这篇关于如何从 XML 中选择特定节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!