我的问题是 Groovy 并在使用 MarkupBuilder 和 XMLSlurper 时附加一个节点。
有人能告诉我为什么当我运行这段代码到第一个 println 时,我的输出将目标行显示为:
<target-line>0</target-line>
但是当我将它运行到第二个 println 时,我的目标行输出现在是:
<target-line>
<target-line>7</target-line>
</target-line>
// Complete code
import groovy.xml.*
public class AppendNodeExample {
//Constructor
public AppendNodeExample() {
}
def CreateNewMessage() {
def dataToProcess = '<response><applied-edits><line><id>0100</id>' +
'<flag><mnemonic>TRA</mnemonic><message>TRA Message ' +
'Info.</message></flag><flag><mnemonic>REB</mnemonic>' +
'<message>REB Message Info.</message><target-line>' +
'<target-line>7</target-line></target-line></flag><flag>'+
'<mnemonic>UNB</mnemonic><message>UNB Message Info.</message>'+
'</flag></line></applied-edits></response>'
def rootNode = new XmlSlurper().parseText(dataToProcess.replaceAll(':','-') )
def newXmlFile = new StringWriter()
def xmlCladNew = new groovy.xml.MarkupBuilder(newXmlFile)
xmlCladNew.response()
{
'applied-edits'()
{
rootNode.'applied-edits'.line.each
{ appliedEditsLine ->
line
{
id(appliedEditsLine.id)
appliedEditsLine.flag.each
{ nodeLineFlag ->
flag
{
mnemonic(nodeLineFlag.mnemonic)
message(nodeLineFlag.message)
'target-line'('0')
}
}
}
}
}
}
def rootNodeNew = new XmlSlurper().parseText(newXmlFile.toString())
// First println
println XmlUtil.serialize(rootNodeNew)
rootNodeNew.'applied-edits'.line.each
{ line ->
line.flag.each
{ lineFlag ->
if (lineFlag.mnemonic == 'REB') {
lineFlag.appendNode({'target-line'('7')})
} else {
// Remove the target-line node
lineFlag.'target-line'.replaceNode {}
}
}
}
XmlUtil.serialize(new StreamingMarkupBuilder().bind {mkp.yield rootNodeNew} )
// Second println
println XmlUtil.serialize(rootNode)
}
}