How can I find a variable string in an XML file using VBS and replace it with another string

I have a config config file containing an encrypted password. From time to time we need to reset this password and this requires excluding the line that is actually the password from the XML file and saves the file.

The process also involves stopping and restarting several services that I can manage, but I have yet to figure out how to find and replace a string as it can be different every time.

I'd love to do this in VBS (because that's pretty much everything I'm familiar with in the scripting world), but I'm happy to consider doing it any other way.

I've looked over the Replace function, but I have yet to find a way to place the template in the search criteria. I need to find:

<A>randomstuff</A>

      

and replace with:

<A></A>

      

For those who may be familiar with the situation, I am returning the password for the Websense Enterprise Manager.

The XML file looks like v1.0:

<?xml version="1.0" encoding="UTF-8"?>

      

Thank. Tom

0


source to share


3 answers


Regular expression perhaps ?



I generally don't recommend them for parsing xml / html files, but if your xml is very specific you are probably fine.

+1


source


Never use regular expressions to parse XML. They are not suitable for this task. The solution you need to look for is XML parsing with VBScript, which is pretty simple.

Here is a sample script that will parse an XML file and replace the text in a specific password element.

Set xml = CreateObject("Msxml2.DOMDocument.6.0")
xml.Load "C:\doc.xml"
Set password = xml.SelectSingleNode("//root/element/password")
password.Text = "Hello, world"
xml.Save "C:\doc.xml"

      



Here is an example XML file that the script will work on.

<root>
    <element>
        <password>Example password</password>
    </element>
</root>

      

An important part of the script is the "SelectSingleNode" method. This uses XPath syntax to search the XML document for the element we want. The XPath syntax is pretty simple, and any number of references to it can be found on the Internet.

+1


source


Or if on your Windows machine it can be even faster and easier with the powershell one line command

(Get-Content doc.xml) -replace '<a>.*</a>','<a></a>' | Set-Content doc.xml

      

And then you'll learn Powershell by adding your resume!

0


source







All Articles