How can I delete a node within a XML file by using vbscript?

Gast1 picture Gast1 · May 18, 2013 · Viewed 8.5k times · Source

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)

Answer

davmos picture davmos · May 18, 2013

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