Link to home
Start Free TrialLog in
Avatar of zequestioner
zequestioner

asked on

VB script to edit XML

Hello Experts,

Can you provide an example way to insert an XML node into an existing XML file?

Currently there is a node within the XML like such: <MyFutureStuff /> and I would like to replace it with the contents of a text file.

The text file would include:

<MyFutureStuff>
      <AllMyFutureStuff>
            <Stuff>
     </AllMyFutureStuff>
</MyFutureStuff>

So, I would like the VB code to REPLACE <MyFutureStuff /> with the XML contents of the file AND if <MyFutureStuff /> doesn't exist, INSERT anyway...
Avatar of Joe Howard
Joe Howard
Flag of United States of America image

If <MyFutureStuff /> doesn't exist where do you want to insert the new xml node?
Avatar of Bill Prew
Bill Prew

This should do the job.  If the tag is there it will replace it, otherwise add the inserted file content to the end.  Adjust the file names near the top as needed.

' Define needed constants
Const ForReading = 1
Const ForWriting = 2
Const TriStateUseDefault = -2

' Define file locations
strMainFile = "main.xml"
strCopyFile = "copy.xml"
strReplace = "<MyFutureStuff />"

' Create file system object
Set objFSO = CreateObject("Scripting.FileSystemObject")

' Read copy file into a string
Set objFile = objFSO.OpenTextFile(strCopyFile, ForReading, False, TriStateUseDefault)
strCopy = objFile.ReadAll
objFile.Close

' Read main file into a string
Set objFile = objFSO.OpenTextFile(strMainFile, ForReading, False, TriStateUseDefault)
strMain = objFile.ReadAll
objFile.Close

' Replace or add the copy file into the main file as needed
If Instr(1, strMain, strReplace, vbTextCompare) Then
   strMain = Replace(strMain, strReplace, strCopy)
Else
   strMain = strMain & strCopy
End If

' Rewrite file with any changes made
Set objFile = objFSO.OpenTextFile(strMainFile, ForWriting, True)
objFile.Write strMain
objFile.Close

Open in new window

~bp
Avatar of zequestioner

ASKER

BP, This works great! Thanks so much for your help!

Only one problem...

The node <MyFutureStuff/> actually exists within <MyXML>...

<MyXml>
   <SomeStuff>
      <MyFutureStuff/>
   </SomeStuff>
</MyXml>

Can you make an edit so that when inserting the XML, it always inserts inside <MyXml> and not at the end of the file? Again, it works great on replacing the text, but if the replacement text doesn't exist, it still needs to insert within <MyXml> and not at the end of the file...

Thanks again!!!
Yes, will be home in a bit and will change that.

~bp
Excellent! So sorry for missing that on the original scope.
Perhaps tomorrow? No rush! Thanks again!
Shortly.

~bp
ASKER CERTIFIED SOLUTION
Avatar of Bill Prew
Bill Prew

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial