VBA_Xpath定位元素


 1 Sub Xpath定位() 'MSXML2.DOMDocument.6.0
 2     Const str_Html As String = _
 3         "<div id = ""outside"">" & _
 4             "<div id =""box"">" & _
 5                 "<div id = ""head"" class = ""color0"">AAA</div>" & _
 6                 "<div id = ""body"" class = ""color1"">BBB</div>" & _
 7                 "<div id = ""footer1"" class = ""color1"">" & _
 8                     "<div id = ""footer2"" class = ""color2"">CCC</div>" & _
 9                 "</div>" & _
10             "</div>" & _
11         "</div>"
12     Dim xmlDom As New MSXML2.DOMDocument60  '引用Microsoft xml,v6.0
13 '    Dim xmlDom As Object
14 '    Set xmlDom = CreateObject("Msxml2.DOMDocument.6.0")
15                                           
16     If Not xmlDom.LoadXML(str_Html) Then
17         MsgBox xmlDom.parseError.reason
18         Set xmlDom = Nothing
19         Exit Sub
20     End If
21     Debug.Print xmlDom.SelectSingleNode("//div/ @ id").Text '根路径下div id
22     Debug.Print xmlDom.SelectSingleNode("//div/div/ @ id").Text
23     Debug.Print xmlDom.SelectSingleNode("//div/div[ @ class = ""color1""]").Text
24     Debug.Print xmlDom.SelectSingleNode("//div/div[ @ id=""body""]").Text
25     Debug.Print xmlDom.SelectNodes("//div/div/@id")(0).Text
26     Debug.Print xmlDom.SelectNodes("//div/div/@id")(2).Text
27     Debug.Print xmlDom.SelectNodes("//div/div[@id=""footer2""]")(0).Text '只有一个结果
28     Debug.Print xmlDom.SelectNodes("//div [@id=""box""] /div [@class=""color1"" ] ")(0).Text
29     Debug.Print xmlDom.SelectNodes("//div/div/@id")(0).XML
30     
31     Set xmlDom = Nothing
32 End Sub

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM