I browsed a lot of different solutions and tried several code lines but couldn't succeed with my example. I'm trying to get the text value (that's ok) of XML nodes, but remain stucked with the node attributes.
Here is my XML:
<MyList>
<Entry Id="33">
<Category>
<Mycategory Style="One">
<Rule Id="37">
<Text>xxx123</Text>
</Rule>
<Rule Id="476">
<Text>123</Text>
</Rule>
</Mycategory>
<Mycategory Style="Two">
<Rule Id="3756">
<Text>xxx456</Text>
</Rule>
<Rule Id="734">
<Text>456</Text>
</Rule>
</Mycategory>
</Category>
<Entry Id="821">
<Category>
<Mycategory Style="One">
<Rule Id="538">
<Text>xxxaaa</Text>
</Rule>
<Rule Id="366">
<Text>aaa</Text>
</Rule>
</Mycategory>
<Mycategory Style="Two">
<Rule Id="894">
<Text>xxxbbb</Text>
</Rule>
<Rule Id="921">
<Text>bbb</Text>
</Rule>
</Mycategory>
</Category>
(etc. until the end of the XML)
I want the following Excel with VBA:
Style One | Style Two
xxx123 | xxx456
xxxaaa | xxxbbb
In extenso: only the text value (beginning with 'xxx') of the first '<'Rule> node. The second '<'Rule> node can be ignored.
All ID="" values are random.
My VBA code:
Sub Parsing()
Dim mainWorkBook As Workbook
Dim XMLFileName, Sheet As String
Dim nodeList As IXMLDOMNodeList
Set mainWorkBook = Workbooks("MyExcel.xlsm")
Set oXMLFile = CreateObject("Microsoft.XMLDOM")
XMLFileName = "C:\MyData.xml"
Sheet = "Sheet1"
oXMLFile.Load (XMLFileName)
Set StyleOne_Nodes = oXMLFile.SelectSingleNode("/MyList/Entry/Category/Mycategory[@name='One']/Rule/Text").Text
Set StyleTwo_Nodes = oXMLFile.SelectSingleNode("/MyList/Entry/Category/Mycategory[@name='Two']/Rule/Text").Text
For i = 0 To (StyleOne_Nodes.Length - 1)
mainWorkBook.Sheets(Sheet).Range("A" & i + 2).Value = StyleOne_Nodes(i).NodeValue
mainWorkBook.Sheets(Sheet).Range("B" & i + 2).Value = StyleTwo_Nodes(i).NodeValue
Next
End Sub
The code fails on SelectSingleNode. I have tried different ways (SelectNodes, SelectSingleNode, getElementsByTagName) but couldn't get my text values (e.g. xxx123 and xxx456) in the excel cells.
Also, looping on the right '<'Rule> is unclear.
How can I get only the '<'Text> value of the first '<'Rule> only (with 'xxx'; ignoring the second '<'Rule>), loop after loop (= '<'Entry> after '<'Entry>)?
Thanks for you help in advance.
@name='One'
to@Style='One'
- Brian M StaffordDim nodeList As IXMLDOMNodeList
is not necessary here. It was for a previous test. I change name->Style, but it says "type incompatibility" on theSet StyleOne_Nodes
line. - Sam77StyleOne_Nodes
defined? Make sure your types match on either side of the=
sign. - Brian M Stafford