Merging a string to XML

360 views Asked by At

I am actually updating a Legacy application in VB 6.0 and I need to add an element to a XML declared as IXMLDOMElement. My XML object's content is actually as follows;

<ChoiceLists>
 <Test Default="*">
  <Choice Value="1" Description="Hours"/>
  <Choice Value="2" Description="Days"/>
 </Test>
</ChoiceLists>

And now I have a query which is already returning me a XML formatted result (as string), as

<Test2 Default="*">
  <Choice Value="276" Description="#276"/>
  <Choice Value="177" Description="#177"/>
  <Choice Value="0000" Description="#0000"/>
  <Choice Value="176" Description="#176"/>
</Test2>

which I need to integrate in my XML, that is in the root node <ChoiceLists>.

Can anyone tell me how do I add this string into my XML please? I've been trying the different functions of the IXMLDOMElement object but in vain.

Thanks

1

There are 1 answers

7
Deanna On BEST ANSWER

You can make use of the IXMLDOMNode.appendChild() method to add one element (and children) to another element. If you have a raw string that you need to convert, you can load that into a new DOMDocument using IXMLDOMDocument.loadXML()

Dim TargetDocument As IXMLDOMDocument
Dim TargetElement As IXMLDOMElement
Dim NewDocument As IXMLDOMDocument
Dim NewElement As IXMLDOMElement

'Load your target document here
Set TargetDocument = New DOMDocument
TargetDocument.Load "P:\iCatcher Console\XML\feedlist.xml"

'Get a reference to the element we want to append to (I'm assuming it's the document element)
Set TargetElement = TargetDocument.DocumentElement

'Create a new documents to parse the XML string
Set NewDocument = New DOMDocument
NewDocument.loadXML NewXMLString

'The root of this document will be the outer element in the string so get a reference to that
Set NewElement = NewDocument.DocumentElement

'Append the new element to the target's children
TargetElement.appendChild NewElement

The resulting XML will now be something like:

<ChoiceLists>
 <Test Default="*">
  <Choice Value="1" Description="Hours"/>
  <Choice Value="2" Description="Days"/>
 </Test>
 <Test2 Default="*">
  <Choice Value="276" Description="#276"/>
  <Choice Value="177" Description="#177"/>
  <Choice Value="0000" Description="#0000"/>
  <Choice Value="176" Description="#176"/>
 </Test2>
</ChoiceLists>