从XML中读取特定代码

时间:2014-07-14 17:57:08

标签: xml vbscript

我对使用VBS读取XML文件并不十分熟悉,所以我需要相当多的手握。我可以获得读取基本XML文件并获取节点名称。但是,我需要读取XML文件,检查子节点是否存在,如果存在,读取值,如果不存在,则创建它。代码如下。

节点" ControllablePreferences"永远存在,子节点" LocalLanAccess"未必。我需要检查" LocalLanAccess"是的,如果是,那么价值是什么,如果不是,我需要将其创建为True。

任何人都可以提供的帮助表示赞赏...

<?xml version="1.0" encoding="UTF-8"?>
<AnyConnectPreferences>
    <DefaultUser>aUser</DefaultUser>
    <DefaultSecondUser></DefaultSecondUser>
    <ClientCertificateThumbprint>#############</ClientCertificateThumbprint>
    <ServerCertificateThumbprint></ServerCertificateThumbprint>
    <DefaultHostName>North America</DefaultHostName>
    <DefaultHostAddress></DefaultHostAddress>
    <DefaultGroup>#########</DefaultGroup>
    <ProxyHost></ProxyHost>
    <ProxyPort></ProxyPort>
    <SDITokenType>software</SDITokenType>
    <ControllablePreferences>
        <LocalLanAccess>true</LocalLanAccess>
    </ControllablePreferences>

编辑 *

我能够使用以下代码完成:

Set oXML = CreateObject("Msxml2.DOMDocument.6.0")
Set oShell = WScript.CreateObject( "WScript.Shell" )
sLocalAppData = oShell.ExpandEnvironmentStrings( "%LOCALAPPDATA%" )
sPrefFile = sLocalAppData & "\Cisco\Cisco AnyConnect Secure Mobility       client\preferences.xml"
sParentNode = "//ControllablePreferences"
sLocalLANAccess = "//ControllablePreferences/LocalLanAccess"

oXML.Async = false
oXML.load(sPrefFile)

If oXML.ParseError <> 0 Then
   WScript.Echo oXML.ParseError.Reason
   WScript.Quit 1
End If

If oXML.SelectNodes(sLocalLANAccess).Length = 0 Then
   WScript.Echo "Node missing."
   Set oRoot = oXML.selectsinglenode (sParentNode)
   Set oRecord = oXML.CreateElement("LocalLanAccess")
   oRoot.AppendChild oRecord
   Set oNode = oXML.selectsinglenode (sLocalLANAccess)
   oNode.text = "true"
   sResult = oXML.Save(sPrefFile)
   WScript.Echo "Updated preferences File"
Else
   Set oNode = oXML.selectsinglenode (sLocalLANAccess)
   if not oNode.Text = LCase("true") then
      oNode.text = "true"
      sResult = oXML.Save(sPrefFile)
      WScript.Echo "Updated preferences File"
   else
      WScript.Echo "Updated not required"
   End if
End If

1 个答案:

答案 0 :(得分:0)

如果需要检查的是节点<LocalLanAccess>的存在,那么应该这样:

Set xml = CreateObject("Msxml2.DOMDocument.6.0")
xml.Async = false
xml.Load "C:\path\to\your.xml"

If xml.ParseError <> 0 Then
  WScript.Echo xml.ParseError.Reason
  WScript.Quit 1
End If

If xml.SelectNodes("//ControllablePreferences/LocalLanAccess").Length = 0 Then
  WScript.Echo "Node missing."
Else
  WScript.Echo "Node present."
End If