使用Groovy的XmlParser解析属性值

时间:2014-06-25 09:08:35

标签: xml groovy xml-parsing

我无法从某些属性中获取值。 下面是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)

我也想知道如何从下面的行获取任何标签值,如(xmlns:xsi) -     

感谢。

2 个答案:

答案 0 :(得分:3)

如果您创建一个限定名称来表示属性的键,那么它将起作用:

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)

或者,您可以将解析器声明为非命名空间,在这种情况下,您可以这样做:

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

答案 1 :(得分:-2)

使用正则表达式查找表达式:

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

如果您只需要获取ID值。它的执行方式比XML解析更好。