0

I need to write a simple VBScript to modify an existing XML file. I am able to write a VBScript to modify an element, but the problem I am currently encountering is that I have multiple elements with the same Element/tag names but different ATTRIBUTES as the below XML document sample shows:

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

Let's assume I wanted to change ONLY the "value" of the parameter "Service" to "LdrXMP.dll" (then save it): Since there is more than one Element called "Section", how would I specify that I am reffering to the Element "Section" whose attribute value = "Second" ??

I have the following simple VBScript code so far: How can I tweak my code below to get what I want? Thanks for your help.

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
  • I recommend using XSLT for this kind of tasks. Pros: Easy, short, readable and maintainable. Cons: None that I know of. Commented Jan 26, 2013 at 22:17

1 Answer 1

1

Use an XPath search expression that referes to the name attribute, selectSingleNode(), and getAttributeNode() as in:

  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

output:

MsrNdp.dll
<MyDoc>
        <Section name="First">
                <Parameter name="Service" value="MsrNdp.dll"/>
        </Section>
        <Section name="Second">
                <Parameter name="Service" value="abracadabra.dll"/>
        </Section>
</MyDoc>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.