1

我有以下 XML 被返回给我:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
  <document xmlns="@link" xmlns:xsi="@link" xsi:schemaLocation="@link" version="1.0">
    <field left="0" top="0" right="100" bottom="20" type="text">
      <value encoding="utf-16">11266</value>
      <line left="8" top="4" right="55" bottom="17">
        <char left="8" top="4" right="13" bottom="16" confidence="65" suspicious="true">1</char>
        <char left="18" top="4" right="23" bottom="16" confidence="68" suspicious="true">1</char>
        <char left="27" top="4" right="35" bottom="16" confidence="100">2</char><char left="36" top="4" right="45" bottom="17" confidence="100">6</char>
        <char left="46" top="4" right="55" bottom="16" confidence="100">6</char>
      </line>
   </field>
</document>

我正在尝试读取value节点。我的代码如下所示:

Dim m_xmld = New XmlDocument()
m_xmld.Load(xmlfile) 
Return m_xmld.SelectSingleNode("/field/value").InnerText

我究竟做错了什么?我也试过/document/field/value无济于事:(

4

2 回答 2

0

尝试从根中选择节点,如下所示:

Dim m_xmld = New XmlDocument()
m_xmld.Load(xmlfile) 

Return FindNode(m_xmld, "value")

尝试使用此功能搜索节点:

Private Function FindNode(list As XmlNodeList, nodeName As String) As XmlNode
    If list.Count > 0 Then
        For Each node As XmlNode In list
            If node.Name.Equals(nodeName) Then
                Return node
            End If
            If node.HasChildNodes Then
                FindNode(node.ChildNodes, nodeName)
            End If
        Next
    End If

    Return Nothing
End Function
于 2013-09-04T17:43:34.120 回答
0

There are two problems with your code. First, you need to specify the XML namespace. The XML document contains a default namespace on the document element (xmlns="@link"). That means that you must explicitly specify that namespace when you reference any element in the document. To do that with XmlDocument, you need to create an XmlNamespaceManager and pass it to the select methods. For instance:

Dim m_xmld As New XmlDocument()
m_xmld.Load(xmlfile)
Dim nsmgr As New XmlNamespaceManager(m_xmld.NameTable)
nsmgr.AddNamespace("x", "@link")
return m_xmld.SelectSingleNode("/x:document/x:field/x:value", nsmgr).InnerText

Or, if you don't want to hard-code the namespace URI, you can just grab it from the loaded document, like this:

nsmgr.AddNamespace("x", m_xmld.DocumentElement.NamespaceURI)

The second problem is that you were trying to select /field/value rather than /document/field/value. When you are selecting from the XmlDocument object, itself, the selection begins from the root of the document ("above" the document element).

于 2013-09-04T19:55:05.400 回答