在Groovy中解析XML

时间:2014-08-23 20:13:11

标签: xml groovy xml-parsing

我已阅读文档,但无法使其正常运行。我想要做的是解析这个XML字符串

<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Body>
        <soapenv:Fault>
            <faultcode>soapenv:Server</faultcode>
            <faultstring>TriggeredMessageFault</faultstring>
            <detail>
                <TriggeredMessageFault xmlns="urn:fault.domain.com">
                    <exceptionCode>INVALID_PARAMETER</exceptionCode>
                    <exceptionMessage>Invalid campaign object</exceptionMessage>
                </TriggeredMessageFault>
            </detail>
        </soapenv:Fault>
    </soapenv:Body>
</soapenv:Envelope>

我尝试做的是转到exceptionCodeexceptionMessage并将其存储在两个不同的变量中。

1 个答案:

答案 0 :(得分:2)

我实际上终于找到了如何做到这一点

def xmlstring = """<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Body>
        <soapenv:Fault>
            <faultcode>soapenv:Server</faultcode>
            <faultstring>TriggeredMessageFault</faultstring>
            <detail>
                <TriggeredMessageFault xmlns="urn:fault.domain.com">
                    <exceptionCode>INVALID_PARAMETER</exceptionCode>
                    <exceptionMessage>Invalid campaign object</exceptionMessage>
                </TriggeredMessageFault>
            </detail>
        </soapenv:Fault>
    </soapenv:Body>
</soapenv:Envelope>"""

def soap_ns = new groovy.xml.Namespace("http://schemas.xmlsoap.org/soap/envelope/",'soapenv')
def root = new XmlParser().parseText(xmlstring)
println root[soap_ns.Body][soap_ns.Fault].detail.TriggeredMessageFault.exceptionMessage.text()

我的问题是双重的。我不知道加载后它是从Envelope开始的,我不知道如何处理命名空间。