VBScript修改一个元素(很多,具有相同的元素名称但具有不同的属性)?

时间:2013-01-26 21:07:14

标签: xml xpath vbscript filter

我需要编写一个简单的VBScript来修改现有的XML文件。我能够编写一个VBScript来修改元素,但我目前遇到的问题是我有多个元素具有相同的元素/标记名称但不同的属性,如下面的XML文档示例所示:

<MyDoc>
   <Section name="First">
      <....../>
  </Section>
  <Section name ="Second">
     <......>
     <Parameter name="Service" value="MsrNdp.dll"/>
   </Section>
 </MyDoc>

我们假设我只想更改&#34;值&#34;参数&#34;服务&#34;到&#34; LdrXMP.dll&#34; (然后保存):由于有多个元素称为&#34; Section&#34;,我如何指定我正在向元素&#34; Section&#34;其属性值=&#34;秒&#34; ??

到目前为止,我有以下简单的VBScript代码:如何调整下面的代码以获得我想要的内容?谢谢你的帮助。

Set xmlDoc = _
  CreateObject("Microsoft.XMLDOM")
xmlDoc.Async = "False"
xmlDoc.Load("C:\Users\Frank\Desktop\MyDoc.xml")
Set colNodes=xmlDoc.selectNodes _
("/MyDoc/Section ")
For Each objNode in colNodes
   objNode.Text = "LdrXMP.dll"
Next
xmlDoc.Save "C:\Users\Frank\Desktop\MyDoc.xml"

1 个答案:

答案 0 :(得分:0)

使用引用name属性的XPath搜索表达式,selectSingleNode()和getAttributeNode(),如下所示:

  Dim oFS      : Set oFS      = CreateObject("Scripting.FileSystemObject")
  Dim sFSpec   : sFSpec       = goFS.GetAbsolutePathName("..\testdata\xml\so14541579.xml")
  Dim objMSXML : Set objMSXML = CreateObject("Msxml2.DOMDocument.6.0")
  objMSXML.setProperty "SelectionLanguage", "XPath"
  objMSXML.async = False

  objMSXML.load sFSpec

  If 0 = objMSXML.parseError Then
     Dim sXPath : sXPath    = "/MyDoc/Section[@name=""Second""]/Parameter"
     Dim ndFnd  : Set ndFnd = objMSXML.selectSingleNode(sXPath)
     If ndFnd Is Nothing Then
        WScript.Echo sXPath, "not found"
     Else
        WScript.Echo ndFnd.getAttributeNode("value").value
        ndFnd.getAttributeNode("value").value = "abracadabra.dll"
        WScript.Echo objMSXML.xml
     End If
  Else
     WScript.Echo objMSXML.parseError.reason
  End If

输出:

MsrNdp.dll
<MyDoc>
        <Section name="First">
                <Parameter name="Service" value="MsrNdp.dll"/>
        </Section>
        <Section name="Second">
                <Parameter name="Service" value="abracadabra.dll"/>
        </Section>
</MyDoc>