user3774346
user3774346

Reputation: 31

Parsing attributes Values using Groovy's XmlParser

I am not able to get values from some of the attributes. Below is the XML:-

def temp="""
 <nodemetadata>
    <imx:IMX xmlns:imx="http://com.abc.imx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-        instance" xmlns:domainservice="http://com.abc.isp.metadata.domainservice/2">
    <domainservice:GatewayNodeConfig imx:id="U:pgwraGgJbC99YpLSQ" consolePort="13993" consoleShutdownPort="4613" domainName="D_1163931" nodeName="N_1163931" dbConnectivity="ID_1">
    <address imx:id="ID_2" xsi:type="common:NodeAddress" host="beetle" httpPort="1391" port="1392"/>
    <portals>
    <NodeRef imx:id="ID_3" xsi:type="common:NodeRef" address="ID_2"     nodeName="N_1163931"/>
    </portals>
    </domainservice:GatewayNodeConfig>
    <domainservice:DBConnectivity imx:id="ID_1"     dbEncryptedPassword="AfaFnEtrQkOKFTVBYIIQ%3D%3D" dbHost="forer" dbName="ORCL" dbPort="1521"     dbType="ORACLE" dbUsername="mka"/>
    </imx:IMX>
</nodemetadata>
        """

def records = new XmlParser().parseText(temp)
def id='imx:id'
//Trying to get the value of imx:id from <domainservice:DBConnectivity >
log.info "Host = "+records.'imx:IMX'.'domainservice:DBConnectivity'[0].attribute(id)

also i would like to know how to get any tag values like (xmlns:xsi) from below lines-

Thanks.

Upvotes: 2

Views: 853

Answers (2)

injecteer
injecteer

Reputation: 20699

Use regexp to find the expression:

"your xml string".eachMatch( /<domainservice:GatewayNodeConfig imx:id="([^"]+)"/ ){ println it[ 1 ] }

if you need to get the id's value only. It performs way better than XML-parsing.

Upvotes: -2

Robby Cornelissen
Robby Cornelissen

Reputation: 97150

It will work if you create a qualified name to represent the attribute's key:

def records = new XmlParser().parseText(temp)
def id = new groovy.xml.QName('http://com.abc.imx', 'id')
println "Host = "+records.'imx:IMX'.'domainservice:DBConnectivity'[0].attribute(id)

Alternatively, you could declare your parser to be non-namespace-aware, and in that case, you can just do this:

def records = new XmlParser(false, false).parseText(temp)
def id = 'imx:id'
println "Host = "+records.'imx:IMX'.'domainservice:DBConnectivity'[0].attribute(id)

Upvotes: 3

Related Questions