Groovy markupBuilder更新父节点 [英] Groovy markupBuilder updating parent node

查看:168
本文介绍了Groovy markupBuilder更新父节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

是否有从子节点访问父节点的优雅方式? / p>

感谢
Tal

解决方案


<有没有一种从子节点访问父节点的优雅方式?


不是用一个MarkupBuilder,它生成XML一种流式方式(在调用嵌套闭包之前,它已经将父元素的开始标记写入输出流)。但是您可以使用 DOMBuilder 构建DOM然后使用DOM API填充总数,最后序列化包含total属性的DOM树:

  import groovy.xml。* 
import groovy.xml.dom。*
import org.w3c.dom。*

def dom = DOMBuilder.newInstance(false,true)
元素parent = dom.parent(){
child(duration:'1')
child(duration:'2')
}
use(DOMCategory){
parent.setAttributeNS(null,totalDuration,
parent.xpath('sum(child / @ duration)'))
}

def xmlString = XmlUtil。序列化(父)

只要不使用DOMBuilder,它应该和MarkupBuilder一样 mkp.yield mkp.yieldUnescaped 在关闭中。如果你需要使用这些,那么你必须建立XML字符串,而不需要 totalDuration 属性,然后将它重新解析为一个DOM,添加额外的属性并重新-serialize。


I'm building xml using MarkupBuilder and wonder how can I update a parent attribute when creating a child node. 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). 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:

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

这篇关于Groovy markupBuilder更新父节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆