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)

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

4 Comments

it says the parameter node is not a child of this node.
Yes sorry, we need to go back up to the parent, then call removeChild(). I've updated the answer.
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 ;-)
No problemo. I should have tested first before answering the first time ;) Can you mark as the answer please.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.