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



>我有以下xml作为字符串:(在这里使用时髦的操场进行快速执行: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>
"""

我想从标签"服务"中提取类型"oracle",这是标签的属性,总是收到错误,这是我尝试运行的代码:

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

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

找到答案:

def xmlParser = new XmlParser().parseText(string)
results = xmlParser.services[0].service[0].@type
println results //Oracle

最新更新