检查XML节点是否已存在

时间:2013-12-09 09:40:04

标签: xml vbscript

我想检查我的VBScript是否已存在XML节点。如果是这种情况,则不应再次添加节点,而应更新数据。有没有办法解决这个问题?这是我的代码:
执行脚本时,将创建一个包含计算机数据的新节点。 (在添加新服务器或硬盘的情况下。)唯一缺少的是,当节点已经存在时,它将使用更新的数据进行更新。

这是我的代码:

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")

任何帮助都会很好!

由于

1 个答案:

答案 0 :(得分:3)

您可以检查特定节点是否已经存在,如下所示:

Set nodes = xmlDoc.SelectNodes("//SERVER[@name='" & strComputerName & "']")
If nodes.Length = 0 Then
  'add node
Else
  'update existing node
End If