[VBS]遍历XML文档

一、脚本源码

使用VBS脚本遍历XML文件

 

 1 Option Explicit 
 2  
 3 '定义常量
 4 Const NodeElement = 1        '元素
 5 Const NodeText = 3           '文本
 6 Const NodeCDATA = 4          'CDATA
 7 Const NodeEntityRef = 5      '实体引用
 8 Const NodeEntity = 6         '实体
 9 Const NodeCommand = 7        '处理指令
10 Const NodeComment = 8        '注释
11 Const NodeDOCTYPE = 10       '文档类型
12  
13 '遍历文件 NameList.xml
14 WScript.Echo VbCrLf
15 WScript.Echo "开始遍历文件 NameList.xml"
16 Dim XDoc
17 Set XDoc = CreateObject("MSXML2.DOMDocument")
18 XDoc.Load("NameList.xml")
19 ReadXmlNode xdoc, 0
20 WScript.Echo "遍历完毕"
21  
22 '递归遍历结点信息 x:结点 lvl:层,从0开始计算
23 Sub ReadXmlNode(x, lvl)
24      
25     Dim gap, child, i
26     gap = Space(lvl * 3)
27  
28     'WScript.Echo gap & "< - - - -"
29  
30     '输出结点类型
31     WScript.Echo gap & "TYPE: " & UCase(x.NodeTypeString), x.NodeName 
32      
33     '遍历属性
34     If x.NodeType = 1 Then 
35         Dim Alist
36         Set Alist = x.Attributes
37         For i = 0 To Alist.Length - 1
38             Dim Attr
39             Set Attr = Alist.Item(i)
40             WScript.Echo gap & "ATTRIBUTE", Attr.NodeName, "=", Attr.NodeValue
41         Next 
42     End If 
43      
44     '如果结点值不为空,显示结点值
45     If Not IsNull(x.NodeValue) Then _
46         WScript.Echo gap & "NODE_VALUE:", "'" & x.NodeValue & "'"
47  
48     '递归遍历子结点
49     If x.HasChildNodes Then 
50         For Each Child In x.ChildNodes
51             ReadXmlNode child, lvl + 1
52         Next
53     End If 
54      
55     'WScript.Echo gap & ">"
56  
57 End Sub

运行结果

打开cmd,使用cscript运行VBS脚本

[VBS]遍历XML文档_第1张图片

 

你可能感兴趣的:([VBS]遍历XML文档)