0

I was having a hard time to think of a way how to find a specific value and modify if found in an XML file. So, I began googling and found an article. However, I can't seem to understand the code that was used as a solution to their problem. I also tried modifying the code but unfortunately I could not make it worked.

<Configuration>
<Add SourcePath="\\sample" ApplicationEdition="32">
    <Product ID="SampleProductID">
      <Language ID="en-us" />
      <Language ID="en-us" />
    </Product>

I need to modify the content of this value <Add SourcePath= I've tried several times and no luck writing a vbscript to change its value. I would appreciate any help and thanks in advance.

xka
  • 53
  • 4
  • 11

2 Answers2

3
  1. Publish complete/valid XML (cf here)
  2. Show the code you have problems with
  3. Link to your sources
  4. Don't use antique tools (XMLDOM vs. msxml2.domdocument)
  5. Avoid spurious () in Sub call
  6. Use basic error handling (cf 1)
  7. Use specific/strict XPath expressions (no // without reason)
  8. Don't use Set x = Nothing just for fun

Demo:

Option Explicit

Dim oXDoc  : Set oXDoc = CreateObject( "Msxml2.DOMDocument" )
oXDoc.setProperty "SelectionLanguage", "XPath"
oXDoc.async = False
oXDoc.load "..\data\31677574.xml"

If 0 = oXDoc.ParseError Then
   WScript.Echo oXDoc.documentElement.xml
   Dim sXPath : sXPath    = "/Configuration/Add"
   Dim ndFnd  : Set ndFnd = oXDoc.selectSingleNode(sXPath)
   If Not ndFnd Is Nothing Then
      ndFnd.getAttributeNode("SourcePath").value = "SomeOtherValue"
      WScript.Echo "----------------", vbCrLf & oXDoc.documentElement.xml
   Else
      WScript.Echo sXPath, "- not found"
   End If
Else
   WScript.Echo oXDoc.ParseError.Reason
End If

output:

cscript 31677574-2.vbs
<Configuration>
        <Add SourcePath="\\sample" ApplicationEdition="32">
                <Product ID="SampleProductID">
                        <Language ID="en-us"/>
                        <Language ID="en-us"/>
                </Product>
        </Add>
</Configuration>
----------------
<Configuration>
        <Add SourcePath="SomeOtherValue" ApplicationEdition="32">
                <Product ID="SampleProductID">
                        <Language ID="en-us"/>
                        <Language ID="en-us"/>
                </Product>
        </Add>
</Configuration>
Community
  • 1
  • 1
Ekkehard.Horner
  • 38,498
  • 2
  • 45
  • 96
0

Try this code

Set xmlDoc = CreateObject("Microsoft.XMLDOM")
xmlDoc.Async = "False"
xmlDoc.Load("T.xml")
Set objAdd = xmlDoc.selectSingleNode("//Configuration/Add")
objAdd.Attributes.getNamedItem("SourcePath").Text = "Test"
xmlDoc.Save "T.xml"
Set objAdd = Nothing
Set xmlDoc = Nothing

I recommend you view these pages

  1. https://technet.microsoft.com/en-us/magazine/2008.02.heyscriptingguy.aspx
  2. https://msdn.microsoft.com/en-us/library/aa468547.aspx
Pankaj Jaju
  • 5,371
  • 2
  • 25
  • 41