1

我在下面有一个简单的 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

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

4

1 回答 1

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 值,如果未找到该属性,则返回一个空字符串。

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

于 2012-08-13T07:20:47.567 回答