![](/img/trans.png)
[英]How to print plain content at the end of node using groovy MarkupBuilder?
[英]Groovy markupBuilder updating parent node
我正在使用MarkupBuilder構建xml,想知道在創建子節點時如何更新父屬性。 假設在構建父元素時無法計算子元素的數量。
def writer = new StringWriter()
def xml = new MarkupBuilder(writer)
xml.parent(totalDuration: 'should be: some of all child duration') {
child(duration: '1')
child(duration: '2')
...
}
是否有一種從子節點訪問父節點的優雅方法?
謝謝塔爾
是否有一種從子節點訪問父節點的優雅方法?
不適用於以流方式生成XML的MarkupBuilder(在調用嵌套閉包之前,它已經將父元素的開始標記寫入了輸出流)。 但是,您可以使用DOMBuilder在內存中構建DOM樹,然后使用DOM API填充總數,最后序列化包含total屬性的DOM樹:
import groovy.xml.*
import groovy.xml.dom.*
import org.w3c.dom.*
def dom = DOMBuilder.newInstance(false, true)
Element parent = dom.parent() {
child(duration:'1')
child(duration:'2')
}
use(DOMCategory) {
parent.setAttributeNS(null, "totalDuration",
parent.xpath('sum(child/@duration)'))
}
def xmlString = XmlUtil.serialize(parent)
只要您沒有在閉包內部使用mkp.yield
或mkp.yieldUnescaped
,DOMBuilder就應該與MarkupBuilder一樣工作。 如果需要使用它們,則必須構建沒有totalDuration
屬性的XML字符串,然后將其重新解析為DOM,添加多余的屬性並重新序列化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.