【问题标题】:Groovy XmlSlurper with special characters in node namesGroovy XmlSlurper 在节点名称中具有特殊字符
【发布时间】:2016-05-04 11:15:54
【问题描述】:

我正在尝试使用 groovy xml slurper 来读取以下 XML,目标是:

<message>ARoute</message> 

标签。

<org.kie.server.api.model.ServiceResponse>
<type>SUCCESS</type>
<msg>Container container2 successfully called.</msg>
<result class="string">
    <execution-results>
    <result identifier="helloWorld">
<com.me.testproject.HelloWorld>
  <message>ARoute</message>
</com.me.testproject.HelloWorld>
</result>
<fact-handle identifier="helloWorld" external-form="0:1:1985641387:1985641387:2:DEFAULT:NON_TRAIT:com.me.testproject.HelloWorld"/>
</execution-results></result>
</org.kie.server.api.model.ServiceResponse>

当我只使用以下 gpath 时:

def response = new XmlSlurper().parseText(payload)
def result = response.result
println( "Output is " + result)

我得到以下(我期望的)

Output is <execution-results>
 <result identifier="helloWorld">
<com.me.testproject.HelloWorld>
  <message>ARoute</message>
</com.me.testproject.HelloWorld>
</result>
<fact-handle identifier="helloWorld" external-  form="0:37:1288414012:1288414012:74:DEFAULT:NON_TRAIT:com.me.testproject.HelloWorld"/>
</execution-results>

但是,当我尝试解析执行结果时,似乎有些问题,我的理解是因为 xml 节点名称中的连字符,我应该把它放在字符中,但这似乎不起作用:

def response = new XmlSlurper().parseText(payload)
def result = response.result.'execution-results'
println( "The type is " + result)

输出: 类型是

我将如何深入研究 XML 消息以获取消息标记?

【问题讨论】:

    标签: xml groovy


    【解决方案1】:

    默认情况下,gpath 表达式的toString() 等价于text() 方法:它只显示表达式匹配的节点的文本内容。简而言之:表达式有效,但您的 println 未显示您的预期。

    如果你想要内容为xml,你可以使用groovy.xml.XmlUtil.serialize(result)

    【讨论】:

    • 感谢您的回复,确实添加了它使其工作。还值得注意的是,我注意到我的 XML 有时会以转义形式出现,使用 org.apache.commons.lang3.StringEscapeUtils 对 XML 字符串进行转义,然后对其进行解析也解决了一些问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-22
    • 1970-01-01
    • 1970-01-01
    • 2015-06-20
    • 1970-01-01
    • 2023-04-03
    相关资源
    最近更新 更多