I need to write a quite large, readable xml file with vba for my work, for which I store the data from several other files in an array. I can't manage to get the individual elements in the right order and the elements from the 2nd loop only appear under the 1st child element, instead of in all of them.
With my code I get the following output so far.
<?xml version="1.0" encoding="UTF-8"?>
<Root name="">
<config type="Typ1">
<item name="It's a Test 1">
</item><item name="It's a Test 2">
</item><item name="It's a Test 3">
</item><item name="It's a Test 4">
</item>
</config><config type="Typ2">
</config><config type="Typ3">
</config>
</Root>
However, the file should actually look like this.
<?xml version="1.0" encoding="UTF-8"?>
<Root name="">
<config type="Typ1">
<item name="It's a Test 1" />
<item name="It's a Test 2" />
<item name="It's a Test 3" />
<item name="It's a Test 4" />
<config type="Typ2">
<item name="It's a Test 1" />
<item name="It's a Test 2" />
<item name="It's a Test 3" />
<item name="It's a Test 4" />
<config type="Typ3">
<item name="It's a Test 1" />
<item name="It's a Test 2" />
<item name="It's a Test 3" />
<item name="It's a Test 4" />
</config>
</Root>
This is the dummy code that goes with it.
Option Base 1
Public Sub Write_XML()
Dim h, i, j As Integer
Dim XML, Root, Child(), Grandchild(), RootAttribut, Attribut() As Object
Dim w(), x(), y() As String
ReDim w(3)
ReDim x(4)
ReDim y(4)
ReDim Attribut(4)
ReDim Child(4)
ReDim Grandchild(4)
w(1) = "Typ1"
w(2) = "Typ2"
w(3) = "Typ3"
For h = 1 To 4
x(h) = "It's a Test " + CStr(h)
Next h
Set XML = CreateObject("MSXML2.DOMDocument")
XML.LoadXML ""
XML.appendChild XML.createProcessingInstruction("xml", "version=""1.0"" encoding=""UTF-8""")
i = 1
j = 1
Set Root = XML.createElement("Root")
Set RootAttribut = XML.createAttribute("name")
RootAttribut.Text = Name
Root.setAttributeNode RootAttribut
Root.appendChild XML.createTextNode(vbNewLine + vbTab)
Do Until i > 3
Set Child(i) = XML.createElement("config")
Set Attribut(i) = XML.createAttribute("type")
Attribut(i).NodeValue = w(i)
Child(i).setAttributeNode Attribut(i)
Child(i).appendChild XML.createTextNode(vbNewLine + vbTab + vbTab)
Do Until j > 4
Set Grandchild(j) = XML.createElement("item")
Set Attribut(j) = XML.createAttribute("name")
Attribut(j).NodeValue = x(j)
Grandchild(j).setAttributeNode Attribut(j)
Grandchild(j).appendChild XML.createTextNode(vbNewLine + vbTab + vbTab)
Child(i).appendChild Grandchild(j)
j = j + 1
Loop
Child(i).appendChild XML.createTextNode(vbNewLine + vbTab)
Root.appendChild Child(i)
i = i + 1
Loop
Root.appendChild XML.createTextNode(vbNewLine)
XML.appendChild (Root)
XML.Save "TestXML.xml"
End Sub
I am quite a beginner with both vba and xml, I hope someone here can help me.