使用XmlSlurper将整个节点检索为字符串

时间:2017-05-18 14:56:18

标签: groovy xmlslurper

我想将false的元素检索为<logs>的数组,我正在尝试以下操作:

String

但是,我得到了这些值,但我希望将整个节点作为文本,或多或少这样:

import groovy.util.XmlSlurper

def payload = '''<logs>
<log>
  <text>LOG 1</text>
  <timestamp>2017-05-18T16:20:00.000</timestamp>
</log>
<log>
  <text>LOG 2</text>
  <timestamp>2017-05-18T16:20:00.000</timestamp>
</log>
</logs>'''

def logs = new XmlSlurper().parseText(payload)
def result = []
logs.log.each{
  result.add(it)
}
result

[<log> <text>LOG 1</text> <timestamp>2017-05-18T16:20:00.000</timestamp> </log>, <log> <text>LOG 2</text> <timestamp>2017-05-18T16:20:00.000</timestamp> </log>] 是否完全可以使用,或者我应该使用一些String操作吗?

3 个答案:

答案 0 :(得分:2)

您可以使用XmlUtil但必须删除xml声明:

import groovy.util.XmlSlurper
import groovy.xml.XmlUtil

def payload = '''<logs>
<log>
  <text>LOG 1</text>
  <timestamp>2017-05-18T16:20:00.000</timestamp>
</log>
<log>
  <text>LOG 2</text>
  <timestamp>2017-05-18T16:20:00.000</timestamp>
</log>
</logs>'''

def logs = new XmlSlurper().parseText(payload)

def result = logs.log.collect { 
  XmlUtil.serialize(it).replaceAll(/<.xml.*?>/,"") 
}

println result

答案 1 :(得分:1)

试试这个:

    def payload = '''<logs>
<log>
  <text>LOG 1</text>
  <timestamp>2017-05-18T16:20:00.000</timestamp>
</log>
<log>
  <text>LOG 2</text>
  <timestamp>2017-05-18T16:20:00.000</timestamp>
</log>
</logs>'''

def logs = new XmlSlurper().parseText(payload)
def result = []
logs.log.each{
  result.add( "<log> <text>" + it?.'text'.text() + "</text> <timestamp> " + it?.'timestamp'.text() + "</timestamp> </log>")
}
return result
​

答案 2 :(得分:1)

你可以选择:

{{1}}