Search code examples
vb.netreadxml

Parse a xml file in Visual basic


which is the best way to parse this xml ???

<?xml version="1.0" encoding="UTF-8"?>
<DOCWARE Version="1.1">
<Order Count="2">
<Pos0>
   <M_TEXTNR>sAuspuffendrohr</M_TEXTNR>
   <VM_BESTNR>s02010000373</VM_BESTNR>    
   <P_PREIS>s715.80</P_PREIS>
</Pos0>
<Pos1>
   <M_TEXTNR>sMutter</M_TEXTNR>      
   <VM_BESTNR>s02010000373</VM_BESTNR>
   <P_PREIS>s0.70</P_PREIS>
</Pos1>
</Order>
<TotalSum>s</TotalSum>
</DOCWARE>

I Try to do so, but is not working then i = 1

Dim xmldoc As New XmlDataDocument()
Dim xmlnode As XmlNodeList
Dim fs As New FileStream(myFileName, FileMode.Open, FileAccess.Read)
xmldoc.Load(fs)
For i As Integer = 0 To 1
  xmlnode = xmldoc.GetElementsByTagName("Pos" & i)
  dim val as string = xmlnode(i).ChildNodes.Item(0).InnerText.Trim()
  MsgBox(val)
Next

thanks in advance


Solution

  • To read a tag with a changed name you can to do using xmlReader and find if you document.Name contains this prefix "Pos", try to use this code:

    Dim document As XmlReader = New XmlTextReader(fileName)
    While (document.Read())
        Dim type = document.NodeType
        If (type = XmlNodeType.Element) Then
          If (document.Name.Contains("Pos")) Then
            Dim test As String = document.ReadInnerXml.ToString()
            Dim doc As New XmlDocument()
            doc.LoadXml("<Pos>" & test & "</Pos>")
            Dim root As XmlNode = doc.FirstChild
            If root.HasChildNodes Then
                dim _value = root.ChildNodes.Item(0).InnerText.Trim()              
            End If
          End If
        End If
    End While