Hi I’m having trouble extracting data from this XML document.
<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>
I need to recursively loop through each message and get the values of the message node. I then need to loop through the attributes and get the value of the attribute nodes if the status is a certain value. I’m having a bit of trouble. So far I have this
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
but i’m having trouble getting the attribute values. I’m sure there must be a cleaner way of doing this too. I was previously using Datasets and was fine until I tried to get to the attributes values
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
It would great if someone could tell me what I’m doing wrong. Which is the best method to use? XMLDocument or a Dataset? Is there an easier way then my longwinded method?
Any help would be great thanks!
You should try
LINQ-XMLImport the System.Data.Xml.