简体   繁体   English

Groovy markupBuilder更新父节点

[英]Groovy markupBuilder updating parent node

I'm building xml using MarkupBuilder and wonder how can I update a parent attribute when creating a child node. 我正在使用MarkupBuilder构建xml,想知道在创建子节点时如何更新父属性。 Assuming the number of child elements cannot be calculated when building the parent element. 假设在构建父元素时无法计算子元素的数量。

 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') 
...  
 }

Is there an elegant way of accessing the parent node from a child node? 是否有一种从子节点访问父节点的优雅方法?

Thanks Tal 谢谢塔尔

Is there an elegant way of accessing the parent node from a child node? 是否有一种从子节点访问父节点的优雅方法?

Not with a MarkupBuilder, which generates the XML in a streaming fashion (it has already written the parent element's opening tag to the output stream before calling the nested closure). 不适用于以流方式生成XML的MarkupBuilder(在调用嵌套闭包之前,它已经将父元素的开始标记写入了输出流)。 But you could use a DOMBuilder to build up a DOM tree in memory, then fill in the total using the DOM API, and finally serialize the DOM tree including the total attribute: 但是,您可以使用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)

The DOMBuilder should work the same as a MarkupBuilder as long as you're not using mkp.yield or mkp.yieldUnescaped inside the closure. 只要您没有在闭包内部使用mkp.yieldmkp.yieldUnescaped ,DOMBuilder就应该与MarkupBuilder一样工作。 If you need to use these then you'd have to build up the XML string without the totalDuration attribute, then re-parse it into a DOM, add the extra attribute and re-serialize. 如果需要使用它们,则必须构建没有totalDuration属性的XML字符串,然后将其重新解析为DOM,添加多余的属性并重新序列化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM