2012-11-27 105 views
2

过去几天我一直在阅读关于使用XML文件的内容,并且正在拉我的头发。替换XML属性值

看起来很容易得到一个属性并更改值,但我无法实现。

我叫input.xml中下面的XML文件:

<gs:GlobalizationService xmlns:gs="urn:longhornGlobalizationUnattend"> 
    <gs:UserList> 
     <gs:User UserID="Current"/> 
    </gs:UserList> 
    <gs:InputPreferences> 
     <gs:InputLanguageID Action="add" ID="0409:00000409" Default="true"/> 
    </gs:InputPreferences> 
</gs:GlobalizationServices> 

我需要能够改变属性ID的价值。看起来好像我应该能够使用selectSingleNode和setAttribute命令的组合来完成这个任务,但我无法实现它。

我一直在尝试的片段如下。值是根据用户选择在主脚本中的其他位置定义的。

Dim xmlDoc, xmlNode 
Set xmlDoc = CreateObject("Microsoft.XMLDOM") 
xmlDoc.Async = "False" 
xmldoc.Load("input.xml") 

Set xmlNode = xmlDoc.selectSingleNode("gs:GlobalizationServices/gs:InputPreferences/gs:InputLanguageID") 
xmlNode.setAttribute "ID", Value 
xmlDoc.save("input.xml") 

回答

0

您应该使用XPath选择器来完成,然后编译选择器。我不认为你需要使用任何第三方库。我认为JDK有你需要做的东西。如果你使用Google,有一些例子。

0

(1)使用的骨架像

Dim oFS : Set oFS = CreateObject("Scripting.FileSystemObject") 
Dim sFSpec : sFSpec = oFS.GetAbsolutePathName("...") 
Dim oXML : Set oXML = CreateObject("Msxml2.DOMDocument") 
oXML.setProperty "SelectionLanguage", "XPath" 
' If namespace(s) 
' oXML.setProperty "SelectionNamespaces", "...'" 
oXML.async = False 
oXML.load sFSpec 
If 0 = oXML.parseError Then 
    WScript.Echo oXML.xml 
    WScript.Echo "-----------------" 
    Dim sXPath : sXPath = "..." 
    Dim ndFnd : Set ndFnd = oXML.selectSingleNode(sXPath) 
    If ndFnd Is Nothing Then 
     WScript.Echo sXPath, "not found" 
    Else 
     WScript.Echo ndFnd.nodeName, ndFnd.getAttribute("UserID") 
     WScript.Echo "-----------------" 
     ndFnd.setAttribute "UserID", "Changed" 
     WScript.Echo oXML.xml 
     oXML.save Replace(sFSpec, ".xml", "-o.xml") 
    End If 
Else 
    WScript.Echo oXML.parseError.reason 
End If 

(2)在文件规范填写后,你意识到你的XML是不是简洁(wellformed)基本错误检查。

script 13589885.vbs 
nd tag 'gs:GlobalizationServices' does not match the start tag 'gs:GlobalizationService'. 

(3)由于XML含有(a)命名空间(S),你需要

oXML.setProperty "SelectionNamespaces", "xmlns:gs='urn:longhornGlobalizationUnattend'" 
... 
Dim sXPath : sXPath = "/gs:GlobalizationService/gs:UserList/gs:User" 

(4),现在它没有明显的分解:

cscript 13589885.vbs 
<gs:GlobalizationService xmlns:gs="urn:longhornGlobalizationUnattend"> 
     <gs:UserList> 
       <gs:User UserID="Current"/> 
     </gs:UserList> 
     <gs:InputPreferences> 
       <gs:InputLanguageID Action="add" ID="0409:00000409" Default="true"/> 
     </gs:InputPreferences> 
</gs:GlobalizationService> 

----------------- 
gs:User Current 
----------------- 
<gs:GlobalizationService xmlns:gs="urn:longhornGlobalizationUnattend"> 
     <gs:UserList> 
       <gs:User UserID="Changed"/> 
     </gs:UserList> 
     <gs:InputPreferences> 
       <gs:InputLanguageID Action="add" ID="0409:00000409" Default="true"/> 
     </gs:InputPreferences> 
</gs:GlobalizationService> 

(5)反映为什么xmldoc.Load("input.xml")xmlDoc.save("input.xml")是错误的VBScript。