Question

I want to remove <P_ID> & <P_Name> nodes from every <product> node.

Here is what the XML looks like:

<products>
 <product>
     <P_ID><![CDATA[4]]></P_ID>
     <Item_T><![CDATA[Pt]]></Item_T>
     <P_Name><![CDATA[5]]></P_Name>
  </product>
  <product>
     <P_ID><![CDATA[4]]></P_ID>
     <Item_T><![CDATA[Pt]]></Item_T>
     <P_Name><![CDATA[5]]></P_Name>
  </product>
  <product>
     <P_ID><![CDATA[4]]></P_ID>
     <Item_T><![CDATA[Pt]]></Item_T>
     <P_Name><![CDATA[5]]></P_Name>
  </product>
  <product>
     <P_ID><![CDATA[4]]></P_ID>
     <Item_T><![CDATA[Pt]]></Item_T>
     <P_Name><![CDATA[5]]></P_Name>
  </product>
</products>

There are thousands of those product nodes.

This is what I have so far:

Set objXMLDoc = Wscript.CreateObject("Microsoft.XMLDOM") 
objXMLDoc.async = False 

Dim XMLFile
XMLFile = "products.xml"
objXMLDoc.load(XMLFile) 
Set nodes = objXMLDoc.selectNodes("products/product/P_ID")
For Each node In nodes
  objXMLDoc.documentElement.remove
Next

objXMLDoc.Save(XMLFile)
Was it helpful?

Solution

You need to reference from the root node in your XPath string by prepending a slash. Then from the parent node you can call the removeChild() method passing the node to remove, like this...

Set nodes = objXMLDoc.selectNodes("/products/product/P_ID | " & _
                                  "/products/product/P_Name")
For Each node In nodes
  node.parentNode.removeChild(node)
Next
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top