Forum Discussion

evoks's avatar
evoks
Occasional Contributor
8 years ago

GroovyScript: Getting node name, sub node names and its values in array from XML

Hi all,

Could you help me please ? 

 

I have an XML file like this :

 

<parent>
    <node1>value1</node1>

    <subnode>

        <subnode1>subnode_value1</subnode1>

    <subnode1>
    <node2>value2</node2>
    <node3>value3</node3>
</parent>

 

Is there a way to get node name, subnode names and his associated value in an array ? 

Output example :

 

    array1 return : [node1, subnode1, node2, node3]

    and array2 return : [value1, subnode_value1, value2, value3]

 

If I get this kind of output, I could work with indexes and compare easily some datas.

 

Many thanks for your future help.

Regards.

  • nmrao's avatar
    nmrao
    Champion Level 3
    Response does not seem to be in well formed.

    why do you want node names in an array?

    May be you can post both xml samples so that it would little more helpful to suggest better.
    • evoks's avatar
      evoks
      Occasional Contributor

      Hi Rao,

      Thanks for your answer.

       

      Indeed, I don't need the node names, it was just a "plus" for me.

       

      I'll try to be more explicit.

       

      If a have two xml :

      File1 :

       

      <File1>                                                                       
          <node1>value1</node1>                                       

          <subnode>                                                                

              <subnode1>subnode_value1</subnode1>

          <subnode1>
          <node2>value2</node2>
          <node3>value3</node3>
      </File1>

       

      Then File2 :

       

      <File2>
          <nodeA>valueA</nodeA>
          <nodeB>valueB</nodeB>
          <nodeC>valueC</nodeC>

          <subnode>

              <subnodeC>subnode_valueC</subnodeC>

          </subnode>
      </File2>

       

      I want to be able to get all values from each xml in two arrays.. Even subnodes.

      After parsing them, for the first XML, I want an output like : "[value1, subnode_value1, value2, value3]"

      And for the second XML : "[valueA, valueB, valueC, subnode_valueC]".

       

      I do not care about value order in arrays.

       

      Do you think is it possible to realize it ? I don't know if it is better to use xmlslurper or another parser?

       

      To conclude, if I have two arrays which contain XML node values, I could be able to compare them with assert :

      (array[a_Value_in_XML_1] == array[other_Value_in_XML_2]

      • nmrao's avatar
        nmrao
        Champion Level 3
        But if the order is different, comparison would fail. Hope you aware that.