如何使用vbscript删除XML文件中的节点?

时间:2021-02-12 01:35:09

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

我想从每个 节点中删除 节点。

Here is what the XML looks like:

这是XML的样子:

<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 个解决方案

#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...

您需要通过添加斜杠来从XPath字符串中的根节点引用。然后从父节点你可以调用removeChild()方法传递要删除的节点,就像这样......

Set nodes = objXMLDoc.selectNodes("/products/product/P_ID | " & _
                                  "/products/product/P_Name")
For Each node In nodes
  node.parentNode.removeChild(node)
Next

#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...

您需要通过添加斜杠来从XPath字符串中的根节点引用。然后从父节点你可以调用removeChild()方法传递要删除的节点,就像这样......

Set nodes = objXMLDoc.selectNodes("/products/product/P_ID | " & _
                                  "/products/product/P_Name")
For Each node In nodes
  node.parentNode.removeChild(node)
Next