在以前的博客中 ,我描述了使用XmlNodePrinter与解析的XML存在XmlParser的一个不错的格式标准输出,为Java String,并且在一个新的文件。 由于XmlNodePrinter
可与groovy.util.Node情况下,它工作得很好XmlParser
,但不那么有效的XmlSlurper因为的XmlSlurper涉及的实例groovy.util.slurpersupport.GPathResult而不是实例groovy.util.Node
。 这篇文章研究了如何使用groovy.xml.XmlUtil来呈现GPathResult
对象, GPathResult
对象是通过将XML提取到标准输出,Java字符串和新文件中而得到的。
这篇文章的第一个代码清单演示啜XML用XmlSlurper
和写入咕噜咕噜GPathResult
使用标准输出XmlUtil
的连载(GPathResult,OutputStream中)方法和System.out的手柄。
slurpAndPrintXml.groovy:将XML写入标准输出
#!/usr/bin/env groovy
// slurpAndPrintXml.groovy
//
// Use Groovy's XmlSlurper to "slurp" provided XML file and use XmlUtil to write
// XML content out to standard output.
if (args.length < 1)
{
println "USAGE: groovy slurpAndPrint.xml <xmlFile>"
}
String xmlFileName = args[0]
xml = new XmlSlurper().parse(xmlFileName)
import groovy.xml.XmlUtil
XmlUtil xmlUtil = new XmlUtil()
xmlUtil.serialize(xml, System.out)
下一个代码清单演示了如何使用XmlUtil
的serialize(GPathResult)方法将GPathResult
序列化为Java String
。
slurpAndSaveXml.groovy:将XML写入Java字符串
#!/usr/bin/env groovy
// slurpXmlToString.groovy
//
// Use Groovy's XmlSlurper to "slurp" provided XML file and use XmlUtil to
// write the XML content to a String.
if (args.length < 1)
{
println "USAGE: groovy slurpAndPrint.xml <xmlFile>"
}
String xmlFileName = args[0]
xml = new XmlSlurper().parse(xmlFileName)
import groovy.xml.XmlUtil
XmlUtil xmlUtil = new XmlUtil()
String xmlString = xmlUtil.serialize(xml)
println "String:\n${xmlString}"
第三个代码清单演示了XmlUtil
的serialize(GPathResult,Writer)方法的使用,该方法通过FileWriter实例将表示已GPathResult
XML的GPathResult
写入文件。
slurpAndPrintXml.groovy:将XML写入文件
#!/usr/bin/env groovy
// slurpAndSaveXml.groovy
//
// Uses Groovy's XmlSlurper to "slurp" XML and then uses Groovy's XmlUtil
// to write slurped XML back out to a file with the provided name. The
// first argument this script expects is the path/name of the XML file to be
// slurped and the second argument expected by this script is the path/name of
// the file to which the XML should be saved/written.
if (args.length < 2)
{
println "USAGE: groovy slurpAndSaveXml.groovy <xmlFile> <outputFile>"
}
String xmlFileName = args[0]
String outputFileName = args[1]
xml = new XmlSlurper().parse(xmlFileName)
import groovy.xml.XmlUtil
XmlUtil xmlUtil = new XmlUtil()
xmlUtil.serialize(xml, new FileWriter(new File(outputFileName)))
这篇文章中的示例演示了如何使用XmlUtil
方法编写/序列化混入GPathResult
对象的XML。 XmlUtil
类还提供用于序列化XmlParser
提供的groovy.util.Node
实例的方法。 接受Node
实例的三种方法与上述GPathResult
实例的三种方法相似。 同样, XmlUtil
其他方法XmlUtil
提供了对XML的类似支持,这些XML表示为org.w3c.dom.Element ,Java String
和groovy.lang.Writable的实例。
我以前的博客文章中介绍的XmlNodePrinter
类可用于序列化XmlParser
解析为Node
XML。 该XmlUtil
类也可以用来连载XmlParser
的解析的XML表示为一个Node
,但提供了能够序列化的额外优势XmlSlurper
的咕噜咕噜XML表示为GPathResult
。