当前位置: 代码迷 >> VB Dotnet >> VB.NET怎么读取XML中的所有节点
  详细解决方案

VB.NET怎么读取XML中的所有节点

热度:74   发布时间:2016-04-25 02:09:30.0
VB.NET如何读取XML中的所有节点
有一个XML内容如下:(只是举个例子,XML的层次可能有很多)

<?xml version="1.0" encoding="gb2312"?>
<doc>
  <A caption="这是A">
      <A1 caption="这是A1"> 
         <A11 caption="这是A11">   
         </A11>  
     </A1> 
     <A2 caption="这是A2">      
     </A2>
  </A>
  <B caption="这是B">
  </B>
  <C caption="这是c">
      <C1 caption="这是c1">
      </C1>
  </C>
</doc>


如何读取每一个节点的caption?
我想得到如下结果:
这是A
  这是A1
    这是A11
  这是A2
这是B
这是C
  这是C1
------解决思路----------------------
使用xpath
//@caption

    Dim xml As New System.Xml.XmlDocument
    xml.Load("F:\testcode\WindowsApplication2\XMLFile1.xml")
    Dim nodes As System.Xml.XmlNodeList = xml.SelectNodes("//@caption")
    For Each node As System.Xml.XmlNode In nodes
      MessageBox.Show(node.Value)
    Next
------解决思路----------------------
Private Function psList(ele As IXMLDOMElement, ByVal iPadding As Integer) As String
    Const IOFFSET As Integer = 2
    
    Dim tmpAttr As IXMLDOMAttribute
    Dim strResult As String
    Dim i As Long
    
    Set tmpAttr = ele.Attributes.getNamedItem("caption")
    If tmpAttr Is Nothing Then
        iPadding = IIf(iPadding < 0, 0 - IOFFSET, iPadding - IOFFSET)
    Else
        strResult = Space(iPadding) & tmpAttr.nodeValue & vbCrLf
    End If
    
    For i = 0 To ele.childNodes.length - 1
        strResult = strResult & psList(ele.childNodes(i), iPadding + IOFFSET)
    Next i
    psList = strResult
End Function
v6.0的。。。
  相关解决方案