解析xml并提取Groovy中子元素的特定属性

时间:2019-05-27 08:37:46

标签: xml groovy xml-parsing

我将以下xml作为字符串:(此处使用groovy操场进行快速执行:https://groovy-playground.appspot.com/

#!groovy
import groovy.util.XmlParser
import groovy.json.JsonSlurper
import groovy.JCIFS.*
import groovy.SmbFile.*

string = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<machine osBit="x64" osVersion="5.6" platform="linux" ip="A.A.A.A" lastTimeIdentified="1553611375772" name="AGENT_NAME" xsi:schemaLocation="" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <ssh xsi:type="sshContext" password="root12" user="root"/>
    <interfaces>
        <interface alias="false" ipAddress="A.A.A.A" name="eth0"/>
    </interfaces>
    <bsx_msi teradataVersionImperva="NOT_TD" uekVersionImperva="NOT_UEK" uname_m="x86_64" uname_n="AGENT_NAME" uname_r="2.6.32-100.26.2.el5" uname_s="Linux" uname_v="#1 SMP Tue Jan 18 20:11:49 EST 2011"/>
    <services>
        <service dbHomePath="/opt/oracle/app/oracle/product/11.2.0/db" dbName="orcl" dbPassword="barbapapa" dbUser="system" dbVersion="11.2.0.1.0" isMariaDB="false" sshPassword="oracle" sshUser="oracle" enabled="true" serviceName="defaultService" **type="Oracle"**>
            <channels>
                <channel xsi:type="machineIdentifierChannelDbAlias" channelType="OracleBEQ" enabled="true">
                    <connections>
                        <connection xsi:type="localConnection" platform="linux" sshPassword="oracle" sshUser="oracle" channelType="OracleBEQ" connectionType="Local" dbName="orcl" dbPassword="barbapapa" dbUser="system" host="A.A.A.A" serviceType="Oracle"/>
                    </connections>
                </channel>
            </channels>
        </service>
    </services>
    <zoneConfiguration/>
</machine>
"""

我想从标签“ service”中提取类型“ oracle”,这是标签的属性,总是出现错误,这是我要运行的代码:

def xmlParser = new XmlParser().parseText(string)
agentPlatform = xmlParser.services.service.attribute("type")
println agentPlatform

这样做的正确形式是什么?

1 个答案:

答案 0 :(得分:1)

找到了答案:

RoleBinding