我有一个org.w3c.dom.Document实例,我需要将其转换为XML字符串。我知道如何在Java中执行此操作(使用javax.xml.transform工具),但我想知道是否有更“常规”的方式来执行此操作?org.w3c.dom.Document to XML string using Groovy
我试过使用DomToGroovy类,它成功地创建了一个groovy脚本版本的DOM文档。但我不知道我将如何使用它来生成一个XML字符串。我可能会吠叫错误的树...
任何帮助将不胜感激!
我有一个org.w3c.dom.Document实例,我需要将其转换为XML字符串。我知道如何在Java中执行此操作(使用javax.xml.transform工具),但我想知道是否有更“常规”的方式来执行此操作?org.w3c.dom.Document to XML string using Groovy
我试过使用DomToGroovy类,它成功地创建了一个groovy脚本版本的DOM文档。但我不知道我将如何使用它来生成一个XML字符串。我可能会吠叫错误的树...
任何帮助将不胜感激!
但我想知道是否有更“常规”的方式来做到这一点?
有肯定的是:类groovy.xml.XmlUtil
我不知道是什么的Groovy的版本中添加这个类的时候,但我想这是一个早期版本。
编辑:class groovy.xml.XmlUtil exists since version 1.6.0;在版本1.5.x中,它被命名为groovy.xml.dom.DOMUtil。在任何一个版本中,这个班都不会做任何事情。如果你看its source,你会发现它只是一个围绕java.xml.transform
的包装。但是,我真的很感谢Groovy GDK提供了一种简单的方法来执行这样的通用操作(将xml写入字符串),而Java JDK无法执行此操作。
例子:
import javax.xml.parsers.DocumentBuilderFactory
import groovy.xml.XmlUtil
def fileName = 'build.xml'
def builder = DocumentBuilderFactory.newInstance().newDocumentBuilder()
def inputStream = new FileInputStream(fileName)
def doc = builder.parse(inputStream)
println XmlUtil.serialize(doc.documentElement)
总是看Groovy API和滚动自己的解决方案(一节课我学到了艰辛的道路)
现在很时髦
> def doc = groovy.xml.DOMBuilder.newInstance().parseText("<foo count='42'><bar/><foo>")
> doc.documentElement as String
<foo count="42">
<bar/>
</foo>
我以前Groovy extensions to the JDK认为它是在Groovy 1.6中添加的。它不在随NetBeans 6.5一起提供的Groovy 1.5中 – Patrick 2009-07-02 16:00:31