使用Groovy的XmlParser解析属性

时间:2011-12-12 12:35:56

标签: xml groovy

我有一个简短的xml我想从中得到一些属性,但是我收到了一些错误

错误

Exception in thread "main" groovy.lang.MissingMethodException: No signature of method: groovy.util.NodeList.attribute() is applicable for argument types: (java.lang.String) values: [dbHost]

我的代码

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 dbHost='dbHost'
println "Host = "+records.'imx:IMX'.'domainservice:DBConnectivity'.attribute("dbHost")

出了什么问题?

1 个答案:

答案 0 :(得分:2)

你不能用:

def attrname = 'dbHost'
println "Host = "+records.'imx:IMX'.'domainservice:DBConnectivity'.@"$attrname"

问题是你有NodeList而不是Node,所以为了让attribute方法有效,你需要做:

// Call attribute on the first Node element
println "Host = "+records.'imx:IMX'.'domainservice:DBConnectivity'[0].attribute( attrname )

或者

// Call attribute on each Node in the NodeList, and return a list of attributes
println "Host = "+records.'imx:IMX'.'domainservice:DBConnectivity'*.attribute( attrname )