VBS按属性名搜索XML节点,更改子属性

时间:2012-08-02 16:25:31

标签: xml vbscript

这是我的XML文件的简化版本:simple.xml

<project>
 <scenes>
  <scene>
   <rootgroup>
    <nodelist>
     <module type="WRITE" name="Write_1080P">
      <option>
       <disabled val="true"/>
      </option>
     </module>
    </nodelist>
   </rootgroup>
  </scene>
 </scenes>
</project>

我需要一个vbscript通过它的属性名称=“Write_1080p”找到正确的“模块”节点,然后将其子节点的属性“val”更改为“disabled”。

应该很简单,但我不熟悉VB中的脚本并且即将发作。

1 个答案:

答案 0 :(得分:1)

这个脚本:

  Dim oFS    : Set oFS  = CreateObject("Scripting.FileSystemObject")
  Dim sFSpec : sFSpec   = oFS.GetAbsolutePathName("..\testdata\xml\so11781815.xml")
  Dim oXML   : Set oXML = CreateObject("Msxml2.DOMDocument")
  oXML.setProperty "SelectionLanguage", "XPath"
  oXML.async = False
  oXML.load sFSpec
  If 0 = oXML.parseError Then
     WScript.Echo oXML.xml
     WScript.Echo "-----------------"
     Dim sXPath : sXPath    = "/project/scenes/scene/rootgroup/nodelist/module[@name=""Write_1080P""]/option/disabled"
     Dim ndFnd  : Set ndFnd = oXML.selectSingleNode(sXPath)
     If ndFnd Is Nothing Then
        WScript.Echo sXPath, "not found"
     Else
        WScript.Echo ndFnd.nodeName, ndFnd.getAttribute("val")
        WScript.Echo "-----------------"
        ndFnd.setAttribute "val", "disabled"
        WScript.Echo oXML.xml
     End If
  Else
     WScript.Echo oXML.parseError.reason
  End If

输出:

<project>
        <scenes>
                <scene>
                        <rootgroup>
                                <nodelist>
                                        <module type="WRITE" name="Write_1080P">
                                                <option>
                                                        <disabled val="true"/>
                                                </option>
                                        </module>
                                </nodelist>
                        </rootgroup>
                </scene>
        </scenes>
</project>

-----------------
disabled true
-----------------
<project>
        <scenes>
                <scene>
                        <rootgroup>
                                <nodelist>
                                        <module type="WRITE" name="Write_1080P">
                                                <option>
                                                        <disabled val="disabled"/>
                                                </option>
                                        </module>
                                </nodelist>
                        </rootgroup>
                </scene>
        </scenes>
</project>

显示了如何使用.setProperty "SelectionLanguage", "XPath"来确保处理XPath查询,如何查询属性值(..t/module[@name=""Write_1080P""]/opt..)以及如何阅读(.getAttribute("val"))和写入( .setAttribute "val", "disabled")属性。

<强> P.S。 查看here以了解如何查找/更改文本(基本上使用相同的代码)。