Separate batch of xml using vb6

54 Views Asked by At

I have a downloaded xml file with several main nodes repeated, how do I separate these nodes into different xml files, using vb6.

This is an example of the xml I'm working with:

<produto>
   <item>
    <codigo>001</codigo>
    <qtde>1</qtde>
   </item>
</produto>

<produto>
   <item>
    <codigo>002</codigo>
    <qtde>33</qtde>
   </item>
</produto>

<produto>
   <item>
    <codigo>004</codigo>
    <qtde>10</qtde>
   </item>
</produto>

<produto>
   <item>
    <codigo>005</codigo>
    <qtde>6</qtde>
   </item>
</produto>

I tried using the following code:

Dim xmldoc As New MSXML2.DOMDocument
Dim noList As MSXML2.IXMLDOMNodeList
Dim node As MSXML2.IXMLDOMNode


xmldoc.loadXML("C:\\test.xml")

Set noList = xmldoc.getElementsByTagName("produto")
For i = 0 To noList.length - 1
    '
    Set node = noList.Item(i)
    xmldoc.loadXML node.nodeValue

    strFile = "Arq_" & i & ".xml"

    node.Save strFile
    '
Next

But there was an error on the line: Set noList = xmldoc.getElementsByTagName("produto")

2

There are 2 best solutions below

0
Hel O'Ween On

As already mentioned, this is not a well-formed XML file, missing a root node. Your XML currently has 4 route nodes produto.

So insert a root node, e.g.

<?xml version="1.0"?>
<root>
    <produto>
         <item>
            <codigo>001</codigo>
            <qtde>1</qtde>
         </item>
    </produto>
    <produto>
         <item>
            <codigo>002</codigo>
            <qtde>33</qtde>
         </item>
    </produto>
    <produto>
         <item>
            <codigo>004</codigo>
            <qtde>10</qtde>
         </item>
    </produto>
    <produto>
         <item>
            <codigo>005</codigo>
            <qtde>6</qtde>
         </item>
    </produto>
</root>

I also personally prefer .selectNodes() over .getElementsByTagName(). It uses a XPath expression, which gives you more control over the selected elements. Not in this particular example, but in general. E.g. for the above example

Set noList = xmldoc.selectNodes("//root/produto")
0
Brian M Stafford On

There are a number of issues with your code.

  1. As mentioned, you must add a root node to your xml file.
  2. You need to use xmldoc.Load when loading the downloaded file.
  3. You need to use node.xml when loading the new document.
  4. You need to use xmldoc.save when saving the new document.

With these changes in place, the code will work like you want:

xmldoc.Load "C:\test.xml"
Set noList = xmldoc.getElementsByTagName("produto")

For i = 0 To noList.length - 1
   Set node = noList.Item(i)
   xmldoc.loadXML node.xml

   strFile = "Arq_" & i & ".xml"

   xmldoc.save strFile
Next