简体   繁体   中英

Object Not Found Parsing XML

I have the following XML being returned to me:

<?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>

I'm trying to read the value node. My code looks like this:

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

What am I doing wrong? I tried /document/field/value as well to no avail :(

Try selecting the node from the root, like this:

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

Return FindNode(m_xmld, "value")

Try using this function to search for the node:

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

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM