1

Need help using a VBscript to edit a single XML file. I've found many examples to edit xml values and I've frankensteined them to edit my xml file, but have not been successful.

My xml file looks like this:

<?xml version="1.0" encoding="utf-8" ?> 
- <configuration>
  <add key="kiosk_identifier" value="PC1" />  
  <add key="kiosk_gui_skin" value="FLA" /> 
  </configuration>

I would like the script to go in and edit value "PC1" to a variable entered by the user in an input box. My bastardized code looks as follows.

Set xmlDoc = _
  CreateObject("Microsoft.XMLDOM")

xmlDoc.Async = "False"
xmlDoc.Load("C:\Scripts\Configuration.xml")

Set colNodes=xmlDoc.selectNodes _
  ("//configuration['@add key'='PC1']")

    strNAME = Inputbox("Enter a hostname:", "Hostname Config", "HOSTNAME")

For Each objNode in colNodes
   objNode.Text = strNAME
Next

xmlDoc.Save "C:\Scripts\Configuration.xml"
user3433578
  • 23
  • 1
  • 1
  • 3
  • 1
    Frankensteining code is the worst way to learn. Make sure you have the VBScript and XML Docs at your finger tips; then reflect upon the difference between nodes/tags vs. attributes, the silliness of expecting to find your root element more than once, and the rules for () in VBScript. Using the "Related" list (or searching before you ask (again)) is also a good idea - http://stackoverflow.com/a/14542079/603855 – Ekkehard.Horner Mar 18 '14 at 15:23

1 Answers1

2

if you have only one node with attribute "value" = PC1 try this

Set colNode = xmlDoc.selectSingleNode("//configuration/add[@value='PC1']")
strNAME = Inputbox("Enter a hostname:", "Hostname Config", "HOSTNAME")
colNode.Attributes.getNamedItem("value").Text = strName
xmlDoc.Save "C:\Scripts\Configuration.xml"

change value of attribute "value" of all nodes with key value "kiosk_identifier":

dim strXPath, colNodes, strNAME, objNode

strXPath = "//configuration/key[@value='kiosk_identifier']"
set colNodes = xmlDoc.DocumentElement.SelectNodes(strXPath)
strNAME = Inputbox("Enter a hostname:", "Hostname Config", "HOSTNAME")

for each objNode in colNodes
  objNode.Attributes.getNamedItem("value").Text = strName
next

xmlDoc.Save "C:\Scripts\Configuration.xml"

P.S the code below was not tested

  • 1
    Works great, but I've used a truncated the XML file and I will have more than one PC1 values. I need to grab the kiosk_identifier variable and change the value of PC1 associated with it. Is that possible? – user3433578 Mar 19 '14 at 12:54
  • 1
    Works like a charm....just changed the strXPath to the following: strXPath = "//configuration/add[@key='kiosk_identifier']" Thank you for all the help! – user3433578 Mar 20 '14 at 15:35