Reputation: 5
I would like to check in my VBScript if an XML node already exists. If this is the case the Node should not be added again, the data should be updated instead. Is there a way I can solve that? Here is my code:
When the script is executed, a new node will be created with the computer data in it. (In the case that a new server or hard disk is added.) Only thing missing is that when the node already exists, it will be updated with more recent data.
Here is my code:
XML:
<?xml version="1.0"?>
<SERVERSPEICHER>
<SERVER name="LANADMIN">
<FESTPLATTE id="1" disk="C:">
<SPEICHER>'450,6'</SPEICHER>
<FREIERSPEICHER>'356,5'</FREIERSPEICHER>
</FESTPLATTE><FESTPLATTE id="2" disk="Q:">
<SPEICHER>'13,7'</SPEICHER>
<FREIERSPEICHER>'3,4'</FREIERSPEICHER>
</FESTPLATTE>
</SERVER>
</SERVERSPEICHER>
VBScript:
on Error Resume Next
Function GetElementFromXmlString(xmlString)
Dim doc
set doc = CreateObject("Microsoft.XMLDOM")
doc.async = False
doc.preserveWhiteSpace= False
doc.loadXML(xmlString)
Set GetElementFromXmlString = doc.documentElement
End Function
Dim xmlDoc, nNode, objNodeList, plot
dim serverNodeItem
dim diskNodeItem
dim diskID
y = 1
id = 1
set objNetwork = CreateObject("WScript.Network")
strComputerName = objNetwork.Computername
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputerName)
Set colDiskSettings = objWMIService.ExecQuery("Select * from Win32_LogicalDisk Where DriveType=3") ' Festplattendaten
Set xmlDOc = CreateObject("Microsoft.XMLDOM")
xmlDoc.Async = "False"
xmlDoc.setProperty "SelectionLanguage", "XPath"
xmlDoc.load "server.xml"
Set objRoot = xmlDoc.documentElement
If Err.Number = 0 Then
Dim xmlString
xmlString = "<SERVER name='"& strComputerName &"'>" & _
"</SERVER>"
Dim newServer
Set newServer = GetElementFromXmlString(xmlString)
objRoot.appendChild(newServer)
Set objServer = xmlDoc.selectsinglenode("//SERVER")
For Each objDisk In colDiskSettings
strDiskDeviceID = objDisk.DeviceID
strDiskSize = FormatNumber((objDisk.Size / (1024 * 1024 * 1024)),1,0,0,0)
strDiskFreeSpace = FormatNumber((objDisk.FreeSpace / (1024 * 1024 * 1024)),1,0,0,0)
Dim xmlDiskString
xmlDiskString = "<FESTPLATTE id='"& id &"' disk='"& strDiskDeviceID &"'>" & _
" <SPEICHER>'"& strDiskSize &"'</SPEICHER>" & _
" <FREIERSPEICHER>'"& strDiskFreeSpace &"'</FREIERSPEICHER>" & _
" </FESTPLATTE>"
If y = id Then
Dim newDisk
Set newDisk = GetElementFromXmlString(xmlDiskString)
objServer.appendChild(newDisk)
End If
id = id + 1
y = y + 1
Next
Else
Err.clear
End If
strResult = xmldoc.save("server.xml")
Any Help would be nice!
Thanks
Upvotes: 0
Views: 2349
Reputation: 200293
You can check if a particular node already exists like this:
Set nodes = xmlDoc.SelectNodes("//SERVER[@name='" & strComputerName & "']")
If nodes.Length = 0 Then
'add node
Else
'update existing node
End If
Upvotes: 3