转载:Easy way to convert XML into Excel - Simple Excel VBA
When I was young I thought, that if You want to send table data You use Excel. Now I know that there are tons of ways of transferring data. One of them is XML. In today’s article I will show You an easy way to convert XML into more user friendly Excel.
# There is not one way of doing this…
I know. There are many methods of reading the XML file, just like in case of HTTP request. My first meeting with this topic was with Microsoft.XMLDOM and I want to introduce You to it, to learn how to read the XML files.
# Example XML structure
For this occasion, specially for You, I prepared simple XML code. Our goal is to create code converting this into Excel table.
1 | <CATALOG> |
# Intro into code
First of all You need to create XML object.
1 | Set xmlfile = CreateObject("Microsoft.XMLDOM") |
If You know the file structure use specified node.
1 | Set ProductNodes = xmlfile.SelectNodes("/CATALOG/PRODUCT") |
In other case, when You don’t really know what You can expect inside, use only slash.
1 | Set ProductNodes = xmlfile.SelectNodes("/") |
To loop through XML tags use For loop. Always start from zero element and iterate to the number of elements minus one.
1 | For i = 0 To ProductNodes.Length - 1 |
Always.
1 | ProductNodes.Length - 1 |
To get the name, type, id or whatever attribute You want to get use .getattribute() method.
1 | .getattribute("name") |
To loop through lower level element use .ChildNodes.
To get child node name use .BaseName and to get its value use .Text.
# Before the code
I would like to mention about procedure I used down below in addition to XML properties and methods I told You above.
To read and transfer this XML data into Excel worksheet table I used 2 loops – for products (i) and for their features (j) (child nodes of products). I got name of the product (.getattribute(“name”)), name of the feature (.ChildNodes(j).BaseName) and its value (.ChildNode(j).Text).
Then using worksheet function .Find I searched for the number of column containing the feature name. In case of no such header I used error handling procedure (On error resume next) to create new column or put the value into existing one.
The result table is below the code.
# Code
1 | Sub main() |
# The result
Product | FEATURE1 | FEATURE2 | FEATURE3 |
---|---|---|---|
A | A1 | A2 | A3 |
B | B1 | B2 | B3 |
C | C1 | C2 | C3 |
# Some words for the end
Of course this is just an example of possible approach to that issue. You could do this in million different ways. I dare You 🙂
Anyway, I hope I explained You most important and needed methods and properties of XMLDOM. Also, that simple example will help You to convert XML into Excel table right now, or in the future when You’ll need it.