1

您好我无法从此 XML 文档中提取数据。

  <messages messageCount="6">
  <message messageID="9999" orderNumber="1234" model="TESTMODEL" val="490" status="8" timestamp="2012-07-12 13:12:50Z">
  <attributes>
  <attribute name="ATT1" value="1234" /> 
  <attribute name="ATT2" value="5678" /> 
  </attributes>
  </message>
  </messages>

我需要递归循环每条消息并获取消息节点的值。然后,如果状态为某个值,我需要遍历属性并获取属性节点的值。我有点麻烦。到目前为止我有这个

        Dim strStream As New MemoryStream(System.Text.Encoding.UTF8.GetBytes(strMessage))

        Dim XmlDoc As XmlDocument = New XmlDocument

        XmlDoc.Load(strStream)


        Dim nlNodeList As XmlNodeList = XmlDoc.SelectNodes("//messages/message")
        Dim a As XmlAttribute

        For Each nNode As XmlNode In nlNodeList
            Dim strmessageID As String = String.Empty
            For Each a In nNode.Attributes
                If a.Name = "messageID" Then
                    strmessageID = a.Value
                End If
            Next
            For Each nChildNode As XmlNode In nNode.ChildNodes
                For Each b In nChildNode.ChildNodes
                    For Each a In b.Attributes
                        If a.Name = "ATT1" Then

                        End If
                    Next
                Next
            Next
        Next

但我无法获取属性值。我敢肯定也必须有一种更清洁的方法。我以前使用数据集并且很好,直到我尝试获取属性值

    For Each dr As DataRow In dsmyDS.Tables("message").Rows
        Dim strMessageID As String = dr.Item("messageid").ToString
        Select Case CStr(dr.Item("model").ToString)
            Case "TESTMODEL"
                Select Case dr.Item("status").ToString
                    Case "8"
                        Dim strval As String = dr.Item("val").ToString
                        'Don't know how to get at the attributes node list once I'm here
                    Case Else

                End Select
            Case Else

        End Select
    Next

如果有人能告诉我我做错了什么,那就太好了。哪个是最好的使用方法?XMLDocument 还是数据集?有没有比我冗长的方法更简单的方法?

任何帮助都会非常感谢!

4

1 回答 1

2

您应该尝试LINQ-XML导入 System.Data.Xml。

 Dim doc As XDocument = XDocument.Load(file)
'Or
'Dim doc As XDocument = XDocument.Parse(strMessage)
 Dim Result = doc.Root.Descendants("message")
                      .Where(Function(p)
                                Return p.Attribute("status").Value = "8"
                             End Function)
 For Each ele In Result
     MsgBox(ele.Attribute("messageID").Value)
     MsgBox(ele.Element("attributes").Element("attribute").Attribute("name").Value)

     'List children of attributes tag
     For Each v In ele.Element("attributes").Elements()
          MsgBox(v.Attribute("name").Value & " " & v.Attribute("value").Value)
     Next
 Next
于 2012-07-13T10:15:37.320 回答