2012-07-13 37 views
1

您好,我无法从此XML文档中提取数据。我需要从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或数据集?那么我有一个更简单的方法,然后我的longwinded方法?

任何帮助将是巨大的感谢!

+0

我觉得你在属性和名称为“属性”的元素之间感到困惑;并且您也在元素的名称和名称为“Name”的元素的属性的值之间感到困惑。 – 2012-07-13 13:33:07

回答

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 
+0

嗨AVD。我传入一个流而不是一个文件,并得到错误“根元素丢失”。当我到达XDocument.Load。 – rborob 2012-07-13 10:59:59

+0

您必须导入'System.Xml.Linq'并使用'XDocument.Parse(stringXml)'加载xmlstring。 – adatapost 2012-07-13 11:01:14

+1

您好,先生,是一个传奇人物。非常感谢!我真的需要刷新我的XML技能! – rborob 2012-07-13 11:10:06

相关问题