【问题标题】:How to get the value of XML attribute using groovy如何使用groovy获取XML属性的值
【发布时间】:2020-05-16 15:07:57
【问题描述】:

我正在尝试在 Groovy 中的 CanOfferProductResponse 标记中获取属性 xmlns 的值

下面是我的 XML-

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <SOAP-ENV:Body><CanOfferProductResponse xmlns="urn:iQQ:API:22:iQQMessages.xsd"/></SOAP-ENV:Body></SOAP-ENV:Envelope>

我尝试了下面的代码,但它不起作用

def Envelope = new XmlSlurper().parseText(xml) 
println Envelope.Body.CanOfferProductResponse.@xmlns

// 预期输出 = urn:iQQ:API:22:iQQMessages.xsd(在 Tag 中)

我是 XML 新手,请帮助我。

【问题讨论】:

    标签: xml groovy xml-parsing xmlslurper


    【解决方案1】:

    XML 名称空间的使用可能会使事情复杂化。如果您知道 XML sn-p 正在使用如图所示的确切名称空间前缀,您可以在 XmlSlurper 中禁用名称空间感知并使用“prefix:elementName”作为引用元素。

    def xml = '''<?xml version="1.0" encoding="UTF-8"?>
    <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
                       xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <SOAP-ENV:Body>
            <CanOfferProductResponse xmlns="urn:iQQ:API:22:iQQMessages.xsd"/>
        </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>
    '''
    
    // the second constructor argument controls namespace awareness
    def env = new XmlSlurper(false, false).parseText(xml)
    def namespace = env.'SOAP-ENV:Body'.CanOfferProductResponse.@xmlns
    assert namespace == 'urn:iQQ:API:22:iQQMessages.xsd'
    

    但是,如果默认命名空间并不总是在 CanOfferProductResponse 元素上定义,或者命名空间前缀并不总是一致,例如Envelope 元素具有xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" 属性而不是xmlns:SOAP-ENV=...,那么这种方法将不起作用。

    命名空间感知方法将涉及调​​用lookupNamespace 方法并传入一个空字符串参数(这意味着该元素的默认命名空间):

    // by default, XmlSlurper instances are namespace aware
    def env = new XmlSlurper().parseText(xml)
    def namespace = env.Body.CanOfferProductResponse.lookupNamespace('')
    assert namespace == 'urn:iQQ:API:22:iQQMessages.xsd'
    

    但由于命名空间是继承的,这种方法意味着 lookupNamespace 方法仍然会返回 'urn:iQQ:API:22:iQQMessages.xsd',即使 @987654329 上实际上没有 xmlns 属性@元素,例如

    def xml = '''<?xml version="1.0" encoding="UTF-8"?>
    <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
                       xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                       xmlns="urn:iQQ:API:22:iQQMessages.xsd">
        <SOAP-ENV:Body>
            <CanOfferProductResponse />
        </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>
    '''
    
    def env = new XmlSlurper().parseText(xml)
    def namespace = env.Body.CanOfferProductResponse.lookupNamespace('')
    assert namespace == 'urn:iQQ:API:22:iQQMessages.xsd'
    

    (此示例使用 Groovy 2.5 执行)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-08
      • 2021-04-30
      • 2013-02-22
      • 1970-01-01
      • 1970-01-01
      • 2013-01-10
      相关资源
      最近更新 更多