使用MarkupBuilder构建静态XML时使用来自XMLParser的数据 [英] Using data from XMLParser while building static XML using MarkupBuilder
问题描述
我想包含从XMLParser检索到的数据并使用MarkupBuilder构建一个新文件。
I want to include data retrieved from an XMLParser and build a new file using the MarkupBuilder.
我很难弄清楚这是如何工作的。
I'm having trouble figuring out how this would work.
C:/file.xml:
C:/file.xml:
<externalData>
<data><nestedData><soOnAndSoForth/></nestedData></data>
</externalData>
Code.groovy:
def writer = new StringWriter()
def xml = new groovy.xml.MarkupBuilder(writer).'root'("id":"foo") {
File content = new File("C:/file.xml")
def externalFile = new XmlParser(false,true,true).parse(content)
// may or may not modify this external data...
externalFile.each { elem -> ${elem} }
'moreData'('id':'myData')
}
println writer.toString()
预期结果:
Expected result:
<root id="foo">
<externalData>
<data><nestedData><soOnAndSoForth/></nestedData></data>
</externalData>
<moreData id="myData">
</root>
我得到:
<root id="foo">
<$ />
<moreData id="myData">
</root>
编辑:如果我在这里采用错误的方法,例如不使用MarkupBuilder并使用其他方法, 让我知道。谢谢!
if I'm taking the wrong approach here, such as not using MarkupBuilder and using something else, let me know. Thanks!
推荐答案
如另一个线程,你可以使用StreamingMarkupBuilder和XmlSlurper来解决这个问题。
As answered in another thread, you can solve this using StreamingMarkupBuilder and XmlSlurper.
如果您需要留在MarkupBuilder中,以下代码将逐字插入到您的xml流中:
If you need to stay with MarkupBuilder the following does a verbatim insert into your xml stream:
import groovy.xml.*
def serialize = { xml ->
def sw = new StringWriter()
new XmlNodePrinter(new PrintWriter(sw)).print(xml)
sw.toString()
}
def writer = new StringWriter()
new MarkupBuilder(writer).'root'("id":"foo") {
def otherXml = new XmlParser(false,true,true).parse(new File('file.xml'))
// may or may not modify this external data...
mkp.yieldUnescaped("\n " + serialize(otherXml).readLines().join("\n "))
'moreData'('id':'myData')
}
println writer.toString()
其中:
where just:
mkp.yieldUnescaped(serialize(otherXml))
就足够了。
以上列印出来:
The above prints out:
<root id='foo'>
<externalData>
<data>
<nestedData>
<soOnAndSoForth/>
</nestedData>
</data>
</externalData>
<moreData id='myData' />
</root>
我们使用XmlNodePrinter而不是XmlUtil.serialize去除xml声明行。 mkp.yieldUnescaped
将一个字符串逐字地插入到xml中。
We use XmlNodePrinter instead of XmlUtil.serialize to get rid of the xml declaration line. mkp.yieldUnescaped
inserts a string verbatim into your xml.
我不会称这个漂亮或健壮,但我认为它完成了这项工作。
I wouldn't call this pretty or robust, but I think it does the job.
这篇关于使用MarkupBuilder构建静态XML时使用来自XMLParser的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!