3

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)
davmos
  • 9,324
  • 4
  • 40
  • 43
Gast1
  • 199
  • 1
  • 3
  • 9

1 Answers1

5

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
davmos
  • 9,324
  • 4
  • 40
  • 43
  • it says the parameter node is not a child of this node. – Gast1 May 18 '13 at 08:28
  • Yes sorry, we need to go back up to the parent, then call `removeChild()`. I've updated the answer. – davmos May 18 '13 at 08:49
  • Try updated answer above. I've also updated the xpath to include both sets of nodes you want to remove. I've also tested it myself this time ;-) – davmos May 18 '13 at 08:53
  • No problemo. I should have tested first before answering the first time ;) Can you mark as the answer please. – davmos May 18 '13 at 08:57