我需要从XML文档中提取数据

时间:2012-07-13 09:56:24

标签: xml vb.net xml-parsing

您好我从此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还是数据集?有没有比我的长途方法更简单的方法?

任何帮助都会非常感谢!

1 个答案:

答案 0 :(得分: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