2012-08-02 97 views
1

這是我的XML文件的一個精簡版:simple.xmlVBS搜索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中的腳本,並且即將發生癲癇發作。

+0

[使用VBS搜索XML並更改值]的可能重複(http://stackoverflow.com/questions/11726266/searching-xml-using-vbs-and-changing-a-value) – 2013-03-13 22:00:19

回答

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看看你如何尋找/更改文本(具有基本相同的代碼)。

+0

不可思議!謝謝Ekkehard。只需要添加'oXML.Save「simple.xml」'來寫入文件。 – Matthr0X 2012-08-03 18:03:42