2017-05-18 52 views
0

字符串我想要檢索的<logs>元素爲String數組,我想以下幾點:檢索整個節點與的XmlSlurper

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>] 

這是與XmlSlurper在所有可能的或者我應該使用一些字符串操作?

回答

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 
+0

我認爲這是最優雅的解決方案,謝謝! –

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 
​ 
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 XmlParser().parseText(payload) 
def result = logs.log.collect { 
    def sw = new StringWriter() 
    def pw = new PrintWriter(sw) 
    new XmlNodePrinter(pw).print(it) 
    sw.toString().replaceAll('\\s', '') 
} 
+0

謝謝,它的偉大工程! –