过去几天我一直在阅读有关处理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 :(得分:0)
您应该使用XPath选择器执行此操作,然后编译选择器。我认为您不需要使用任何第三方库。我认为JDK有你需要的东西。如果您使用谷歌就有例子。
答案 1 :(得分: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格式不正确。
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。