tags:

views:

60

answers:

1

I have the following VB script , I want to remove the "NET2 ID" element from name list how to remove the NET2 ID element , need first to verify if NET2 defined and then to delete it THX

Set objXMLDoc = CreateObject("Microsoft.XMLDOM") 
objXMLDoc.async = False 
objXMLDoc.load("\\dir\d.xml") 
Set objRoot = objXMLDoc.documentElement 
Set objExNode = objRoot.removeChild(objRoot.childNodes.item(1)) 

the XML file:

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<root version="3.0">
<names> 
<NET1 ID="10.10.10.1-10" />
<NET2 ID="10.10.10.1-10" />
</names>
</root>
A: 

You can use XPath to determine if the node exists then remove it. Something like this:

Set objXMLDoc = CreateObject("Microsoft.XMLDOM")  
objXMLDoc.async = False  
objXMLDoc.load("\\dir\d.xml")  
Set objRoot = objXMLDoc.documentElement  

If Not objRoot.selectSingleNode("./names/NET2") Is Nothing Then
    Set objExNode = objRoot.firstChild.removeChild(objRoot.firstChild.childNodes(1))  
End If

Also, the element NET2 is a child of "names" and not "root", which is the documentElement, so

Set objExNode = objRoot.removeChild(objRoot.childNodes.item(1)) 

becomes

Set objExNode = objRoot.firstChild.removeChild(objRoot.firstChild.childNodes(1))  

EDIT: To add a new node you would do the following. 1 means NODE_ELEMENT

Set newNode = objXMLDoc.createNode(1, "NET3", "")
Set id = objXMLDoc.createAttribute("ID")
id.Value = "newIDValue"
newNode.attributes.setNamedItem(id)

objRoot.firstChild.appendChild(newNode)
Garett
OK after I remove the NET2... How to append new child as: <NET3 ID="11.11.10.1-10" /> to names?
yael
You can use the createNode method of the objXMLDoc then append it to the names node. See the documentation here: http://msdn.microsoft.com/en-us/library/ms757901(v=VS.85).aspx
Garett
yes but I am not understand how to create it under names?can you give me exampleTHX
yael
I updated the answer with an example of how to add a new child.
Garett