在Visual Basic中解析xml文件

时间:2015-02-20 15:38:45

标签: vb.net readxml

这是解析这个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 = 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

提前致谢

1 个答案:

答案 0 :(得分:1)

要读取具有更改名称的标记,您可以使用xmlReader进行操作,并查找document.Name是否包含此前缀&#34; Pos&#34;,尝试使用此代码:

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