In groovy Xpath function not working for a xml

Viewed 39

I am having the below XML:

<orders>
    <order xmlns:amz="http://www.amazon.co">
        <amz:comp>amz</amz:comp>
    </order>
    <order xmlns:ebay="http://www.ebay.co">
        <ebay:comp>ebay</ebay:comp>
    </order>
</orders>

I checked the xpath expressions like //orders/order it is working but in groovy it is not working I'm not getting what is wrong.

Below is the code that I am using: import groovy.xml.*;

def source = '''<orders>
    <order xmlns:amz="http://www.amazon.co">
        <amz:comp>amz</amz:comp>
    </order>
    <order xmlns:ebay="http://www.ebay.co">
        <ebay:comp>ebay</ebay:comp>
    </order>
</orders>'''

def root = new XmlSlurper().parseText(source).declareNamespace([
    amz: "http://www.amazon.co",
    ebay: "http://www.ebay.co"
])

println root.orders
println root.orders.order."amz:comp"

I am not getting any output for the above code.

1 Answers

In your example, root variable refers to the <orders> element, so when you call root.orders it is like you were looking for

<orders>
    <orders>...</orders>
</orders>

Rename root variable to orders and do

println orders
println orders.order."amz:comp"

to get the following output:

amzebay
amz
Related