【问题标题】:Reading an attribute through XPath in xml document does not work在 xml 文档中通过 XPath 读取属性不起作用
【发布时间】:2012-08-09 09:24:01
【问题描述】:

下面有一个简单的xml文档:

    <?xml version="1.0" encoding="utf-8"?>
<Research researchID="RT_a" language="eng" xmlns="http://www.rixml.org/2010/1/RIXML" createDateTime="2012-06-30T01:13:38Z">
  <Product productID="RT_a">
              <SecurityID idType="ISIN" idValue="US0605051046" />
  </Product>
</Research>

我正在尝试使用给定的 XPath 字符串读取属性“idValue”。除非我删除这部分,否则这不起作用:

xmlns="http://www.rixml.org/2010/1/RIXML" 

我的代码如下:

    Dim doc As XPathDocument = New XPathDocument("c:\test\test.xml")

    Dim strXPath As String = "/Research[1]/Product[1]/SecurityID[1]"
    Dim nav As XPathNavigator = doc.CreateNavigator()
    Dim mgr As New XmlNamespaceManager(nav.NameTable)

    mgr.AddNamespace("", "http://www.rixml.org/2010/1/RIXML")

    Dim XPathNode As XPathNavigator = nav.SelectSingleNode(strXPath, mgr)
    If XPathNode IsNot Nothing Then
        Console.WriteLine(XPathNode.GetAttribute("idValue", String.Empty))
    Else
        Console.WriteLine("Nothing found")
    End If

关于添加名称空间的行对结果没有影响 - 只是做了一些测试。我需要做什么/我做错了什么?

【问题讨论】:

    标签: xml vb.net xpath


    【解决方案1】:

    尝试以下方法:

    Dim strXPath As String = "/x:Research[1]/x:Product[1]/x:SecurityID[1]/@idValue"
    Dim nav As XPathNavigator = doc.CreateNavigator()
    Dim mgr As New XmlNamespaceManager(nav.NameTable)
    
    mgr.AddNamespace("x", "http://www.rixml.org/2010/1/RIXML")
    nav.Evaluate("string(" + strXPath + ")", mgr)
    

    它应该返回您的 ID 值,如果未找到该属性,则返回一个空字符串。

    我认为问题可能出在here 列出的那个,您必须明确引用命名空间(即使它是默认命名空间),因此使用“x:”可以修复它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-17
      • 1970-01-01
      • 1970-01-01
      • 2016-02-22
      • 1970-01-01
      • 1970-01-01
      • 2014-06-29
      • 2021-10-04
      相关资源
      最近更新 更多