如何从 XML 中选择特定节点 [英] How to select particular node from XML

查看:27
本文介绍了如何从 XML 中选择特定节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 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

错误

未将对象引用设置为对象的实例.

Object reference not set to an instance of an object.

编辑

我知道我收到此错误是由于 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 :

  1. 使用简洁语法解析 XML
  2. 将 XPath 与 XML 命名空间结合使用
  3. 获取单节点收益值"...Nothing 的价值"

这是使用 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 中选择特定节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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