-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathExcel VBA - XML.vb
124 lines (84 loc) · 2.73 KB
/
Excel VBA - XML.vb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
http://szxml.blogspot.fr/2012/04/writing-xml-in-vba.html
http://stackoverflow.com/questions/20020990/looping-through-xml-using-vba
Import 'Microsoft XML, v6.0'
Sub read_Single_Node_XML()
dim xDoc As IXMLDOMDocument2
Set xDoc = New MSXML2.DOMDocument60
file_Path = "D:\HTML\Exercises\VBA"
xDoc.Load file_Path & "\stars.xml"
Dim list As IXMLDOMNodeList
Set list = xDoc.SelectNodes("//stars/kendall")
Dim attr As IXMLDOMAttribute
Dim node As IXMLDOMNode
'*If children
'Dim childNode As IXMLDOMNode
'Set node = list.NextNode OR...
Set node = list.Item(0).SelectSingleNode("name")
'*If children
Set childNode = node.FirstChild
MsgBox childNode.Text
End Sub
'
'Write XML
Sub write_XML_File()
Dim xDoc As Object
Set xDoc = CreateObject("MSXML2.DOMDocument")
xDoc.async = False
xDoc.validateOnParse = False
file_Path = "D:\HTML\Exercises\VBA"
xDoc.Load file_Path & "\stars.xml"
Dim list As IXMLDOMNodeList
Set list = xDoc.SelectNodes("//stars/kendall")
Dim write As IXMLDOMElement
Set write = xDoc.createElement("eyes")
write.Text = "Blue"
list.Item(0).appendChild write
'Save file
xDoc.Save file_Path & "\stars.xml"
Set xDoc = Nothing
End Sub
'
'Delete a child
Sub delete_Child()
Dim xDoc As Object
Set xDoc = CreateObject("MSXML2.DOMDocument")
xDoc.async = False
xDoc.validateOnParse = False
file_Path = "D:\HTML\Exercises\VBA"
xDoc.Load file_Path & "\stars.xml"
Dim list As IXMLDOMNodeList
Set list = xDoc.SelectNodes("//stars/kendall")
Dim delete_Node As IXMLDOMElement
Set delete_Node = list.Item(0).SelectSingleNode("eyes")
list.Item(0).RemoveChild delete_Node
xDoc.Save file_Path & "\stars.xml"
Set xDoc = Nothing
End Sub
'
' Change node value
Sub change_Node_Value()
Dim xDoc As IXMLDOMDocument2
Set xDoc = New MSXML2.DOMDocument60
xDoc.Load "D:\HTML\Exercises\VBA\stars.xml"
xDoc.async = False
xDoc.validateOnParse = False
Dim list As IXMLDOMNodeList
Set list = f.SelectNodes("//stars/kendall")
Dim write_v As IXMLDOMElement
Set write_v = list.Item(0).LastChild
write_v.Text = "Blue"
list.Item(0).appendChild write_v
f.Save "D:\HTML\Exercises\VBA\stars.xml"
Set f = Nothing
End Sub
Sub get_Attribute()
Dim n As MSXML2.IXMLDOMDocument2
Set n = New MSXML2.DOMDocument60
n.Load ("D:\HTML\VBA codes\init.xml")
Dim l As IXMLDOMNodeList
Set l = n.SelectNodes("//.../...")
Debug.Print l.Item(0).Attributes.getNamedItem("...").Text
Set n = Nothing
Set l = Nothing
Set j = Nothing
End Sub