2012-07-13 66 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