The CreatorCon Call for Content is officially open! Get started here.

Retrieve nodes with same name in a XML file

andreazaffaroni
Tera Expert

<?xml version="1.0" encoding="UTF-8" ?>
<test>
         <one>
                   <two>A</two>
                  <three>B</three>
        </one>
        <one>
                  <two>C</two>
                  <three>D</three>
         </one>
</test>

Hi Community,

Can you please help me to retrieve data "A" and "C" from the correspondent childNodes "two" when the parentNode has the same name. See the example above.

Thanks,

Andrea

 

1 ACCEPTED SOLUTION

Please try this out, I have tested

var xmlString = "<test><one><two>A</two><three>B</three></one><one><two>C</two><three>D</three></one></test>";
var xmlDoc = new XMLDocument2();
xmlDoc.parseXML( xmlString ); 
node = xmlDoc.getFirstNode( '//test/one/two' );
j=1;
while( node != null ) {
      var value = xmlDoc.getNodeText( '//test/one[' + j + ']/two');
       gs.info( 'Value: ' + value);
       j++;
       node = xmlDoc.getNextNode( node );
}

View solution in original post

8 REPLIES 8

Hi,

I am currently using XMLDocument2 is it the same as XMLDocument? 

Thanks,

Andrea

Alikutty A
Tera Sage

Hello Andrea,

You can try this out

var doc = new XMLDocument('Your XML String');
var nodes = doc.getNodes('//test/one');
for(var i=0; i < nodes.length; i++){
var value = nodes.item(i).getNodeValue();
gs.print(value);
}

If you need to access node two, then replace

var nodes = doc.getNodes('//test/two');

Hi,

I am currently using XMLDocument2 is it the same as XMLDocument? 

Thanks,

Andrea