xml - 如何使用groovy获取XML属性的值
问题描述
我正在尝试在 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 名称空间的使用可能会使事情复杂化。如果您知道 XML 片段正在使用所示的确切名称空间前缀,您可以在 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” ,例如xmlns
CanOfferProductResponse
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 执行)
推荐阅读
- html - 根据设备方向转置 HTML 表格
- wcf - 作为服务引用添加的 WCF 服务显示为缺少 DataContracts 的连接服务
- python - 使用 pd.melt 时如何保留索引并合并为 Seaborn 和 matplotlib 创建 DataFrame
- asp.net-mvc - NLog 可扩展性 - 如何使用 ExtendValues 添加自定义字段?
- c# - 更改可写支持字段后,C# 中的只读属性永远不会更新
- labview - 使用 Labview 在字符串中替换 (., space, -, ) 的正则表达式是什么
- python - 最大对明智产品python
- r - 使用方差分析比较两个样本量不等的线性模型:错误
- haskell - 做符号和绑定签名
- python - 通过使用 NumPy 对 2 个数组元素数组进行求和来形成矩阵