Groovy XML support library providing comprehensive XML processing capabilities including parsing, manipulation, and generation of XML documents using Groovy's native XML handling features, XmlSlurper, and XmlParser APIs
—
Utility functions for XML serialization, pretty printing, escaping, and advanced parser configuration with schema validation support. Essential tools for XML processing workflows.
Comprehensive utility class providing serialization, pretty printing, and XML processing utilities for various XML object types.
/**
* Serialize DOM Element to formatted XML string
* @param element - DOM Element to serialize
* @return Pretty-printed XML string
*/
static String serialize(Element element)
/**
* Serialize DOM Element with DOCTYPE control
* @param element - DOM Element to serialize
* @param allowDocTypeDeclaration - Whether to allow DOCTYPE declarations
* @return Pretty-printed XML string
*/
static String serialize(Element element, boolean allowDocTypeDeclaration)
/**
* Serialize DOM Element to OutputStream
* @param element - DOM Element to serialize
* @param os - OutputStream for output
*/
static void serialize(Element element, OutputStream os)
/**
* Serialize DOM Element to OutputStream with DOCTYPE control
* @param element - DOM Element to serialize
* @param os - OutputStream for output
* @param allowDocTypeDeclaration - Whether to allow DOCTYPE declarations
*/
static void serialize(Element element, OutputStream os, boolean allowDocTypeDeclaration)
/**
* Serialize DOM Element to Writer
* @param element - DOM Element to serialize
* @param writer - Writer for output
*/
static void serialize(Element element, Writer writer)
/**
* Serialize DOM Element to Writer with DOCTYPE control
* @param element - DOM Element to serialize
* @param writer - Writer for output
* @param allowDocTypeDeclaration - Whether to allow DOCTYPE declarations
*/
static void serialize(Element element, Writer writer, boolean allowDocTypeDeclaration)/**
* Serialize groovy.util.Node to formatted XML string
* @param node - Node to serialize
* @return Pretty-printed XML string
*/
static String serialize(Node node)
/**
* Serialize groovy.util.Node to OutputStream
* @param node - Node to serialize
* @param os - OutputStream for output
*/
static void serialize(Node node, OutputStream os)
/**
* Serialize groovy.util.Node to Writer
* @param node - Node to serialize
* @param writer - Writer for output
*/
static void serialize(Node node, Writer writer)/**
* Serialize GPathResult to formatted XML string
* @param gPathResult - GPathResult to serialize
* @return Pretty-printed XML string
*/
static String serialize(GPathResult gPathResult)
/**
* Serialize GPathResult to OutputStream
* @param gPathResult - GPathResult to serialize
* @param os - OutputStream for output
*/
static void serialize(GPathResult gPathResult, OutputStream os)
/**
* Serialize GPathResult to Writer
* @param gPathResult - GPathResult to serialize
* @param writer - Writer for output
*/
static void serialize(GPathResult gPathResult, Writer writer)/**
* Serialize Writable object to formatted XML string
* @param writable - Writable object to serialize
* @return Pretty-printed XML string
*/
static String serialize(Writable writable)
/**
* Serialize Writable object to OutputStream
* @param writable - Writable object to serialize
* @param os - OutputStream for output
*/
static void serialize(Writable writable, OutputStream os)
/**
* Serialize Writable object to Writer
* @param writable - Writable object to serialize
* @param writer - Writer for output
*/
static void serialize(Writable writable, Writer writer)/**
* Pretty-print XML string
* @param xmlString - XML string to format
* @return Pretty-printed XML string
*/
static String serialize(String xmlString)
/**
* Pretty-print XML string with DOCTYPE control
* @param xmlString - XML string to format
* @param allowDocTypeDeclaration - Whether to allow DOCTYPE declarations
* @return Pretty-printed XML string
*/
static String serialize(String xmlString, boolean allowDocTypeDeclaration)
/**
* Pretty-print XML string to OutputStream
* @param xmlString - XML string to format
* @param os - OutputStream for output
*/
static void serialize(String xmlString, OutputStream os)
/**
* Pretty-print XML string to OutputStream with DOCTYPE control
* @param xmlString - XML string to format
* @param os - OutputStream for output
* @param allowDocTypeDeclaration - Whether to allow DOCTYPE declarations
*/
static void serialize(String xmlString, OutputStream os, boolean allowDocTypeDeclaration)
/**
* Pretty-print XML string to Writer
* @param xmlString - XML string to format
* @param writer - Writer for output
*/
static void serialize(String xmlString, Writer writer)
/**
* Pretty-print XML string to Writer with DOCTYPE control
* @param xmlString - XML string to format
* @param writer - Writer for output
* @param allowDocTypeDeclaration - Whether to allow DOCTYPE declarations
*/
static void serialize(String xmlString, Writer writer, boolean allowDocTypeDeclaration)/**
* Create SAXParser with schema validation
* @param schemaLanguage - Schema language (e.g., XMLConstants.W3C_XML_SCHEMA_NS_URI)
* @param schemas - Schema sources for validation
* @return Configured SAXParser
*/
static SAXParser newSAXParser(String schemaLanguage, Source... schemas)
/**
* Create SAXParser with full configuration control
* @param schemaLanguage - Schema language
* @param namespaceAware - Enable namespace processing
* @param validating - Enable DTD validation
* @param schemas - Schema sources for validation
* @return Configured SAXParser
*/
static SAXParser newSAXParser(String schemaLanguage, boolean namespaceAware, boolean validating, Source... schemas)
/**
* Create SAXParser with complete configuration
* @param schemaLanguage - Schema language
* @param namespaceAware - Enable namespace processing
* @param validating - Enable DTD validation
* @param allowDoctypeDecl - Allow DOCTYPE declarations
* @param schemas - Schema sources for validation
* @return Configured SAXParser
*/
static SAXParser newSAXParser(String schemaLanguage, boolean namespaceAware, boolean validating, boolean allowDoctypeDecl, Source... schemas)
/**
* Create SAXParser with File-based schema
* @param schemaLanguage - Schema language
* @param schema - Schema file
* @return Configured SAXParser
*/
static SAXParser newSAXParser(String schemaLanguage, File schema)
/**
* Create SAXParser with File-based schema and configuration
* @param schemaLanguage - Schema language
* @param namespaceAware - Enable namespace processing
* @param validating - Enable DTD validation
* @param schema - Schema file
* @return Configured SAXParser
*/
static SAXParser newSAXParser(String schemaLanguage, boolean namespaceAware, boolean validating, File schema)
/**
* Create SAXParser with URL-based schema
* @param schemaLanguage - Schema language
* @param schema - Schema URL
* @return Configured SAXParser
*/
static SAXParser newSAXParser(String schemaLanguage, URL schema)
/**
* Create SAXParser with URL-based schema and configuration
* @param schemaLanguage - Schema language
* @param namespaceAware - Enable namespace processing
* @param validating - Enable DTD validation
* @param schema - Schema URL
* @return Configured SAXParser
*/
static SAXParser newSAXParser(String schemaLanguage, boolean namespaceAware, boolean validating, URL schema)/**
* Escape special XML characters in string
* @param text - Text to escape
* @return XML-escaped string
*/
static String escapeXml(String text)
/**
* Escape control characters in string
* @param text - Text to escape
* @return String with control characters escaped
*/
static String escapeControlCharacters(String text)/**
* Safely set feature on TransformerFactory (ignores exceptions)
* @param factory - TransformerFactory to configure
* @param feature - Feature name
* @param value - Feature value
*/
static void setFeatureQuietly(TransformerFactory factory, String feature, boolean value)
/**
* Safely set feature on DocumentBuilderFactory (ignores exceptions)
* @param factory - DocumentBuilderFactory to configure
* @param feature - Feature name
* @param value - Feature value
*/
static void setFeatureQuietly(DocumentBuilderFactory factory, String feature, boolean value)
/**
* Safely set feature on SAXParserFactory (ignores exceptions)
* @param factory - SAXParserFactory to configure
* @param feature - Feature name
* @param value - Feature value
*/
static void setFeatureQuietly(SAXParserFactory factory, String feature, boolean value)Usage Examples:
import groovy.xml.*
import javax.xml.XMLConstants
import javax.xml.transform.stream.StreamSource
import org.w3c.dom.Element
// Serialization examples
def parser = new XmlParser()
def node = parser.parseText('''
<library>
<book id="1">
<title>Groovy Guide</title>
<author>Expert</author>
</book>
</library>
''')
// Serialize Node to pretty-printed string
String prettyXml = XmlUtil.serialize(node)
println prettyXml
// Serialize to file
new File("output.xml").withWriter { writer ->
XmlUtil.serialize(node, writer)
}
// Serialize to OutputStream with encoding
new FileOutputStream("output.xml").withStream { stream ->
XmlUtil.serialize(node, stream)
}
// Serialize GPathResult
def slurper = new XmlSlurper()
def gpath = slurper.parseText('<data><item>test</item></data>')
String gPathXml = XmlUtil.serialize(gpath)
println gPathXml
// Pretty-print existing XML string
String uglyXml = '<root><child>text</child></root>'
String formatted = XmlUtil.serialize(uglyXml)
println formatted
// DOM serialization
def builder = DOMBuilder.newInstance()
def doc = builder.catalog { item("Sample") }
Element rootElement = doc.documentElement
String domXml = XmlUtil.serialize(rootElement)
println domXml
// Schema validation with SAXParser
def schemaFile = new File("schema.xsd")
def parser = XmlUtil.newSAXParser(
XMLConstants.W3C_XML_SCHEMA_NS_URI,
true, // namespace aware
true, // validating
schemaFile
)
// Multiple schema sources
def schema1 = new StreamSource(new File("schema1.xsd"))
def schema2 = new StreamSource(new File("schema2.xsd"))
def validatingParser = XmlUtil.newSAXParser(
XMLConstants.W3C_XML_SCHEMA_NS_URI,
schema1, schema2
)
// XML escaping
String unsafe = '<script>alert("hack")</script> & "quotes"'
String safe = XmlUtil.escapeXml(unsafe)
println safe // <script>alert("hack")</script> & "quotes"
// Control character escaping
String withControlChars = "Text\u0001with\u0002control\u0003chars"
String escaped = XmlUtil.escapeControlCharacters(withControlChars)
println escaped
// Feature configuration (safe)
import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.transform.TransformerFactory
def docFactory = DocumentBuilderFactory.newInstance()
XmlUtil.setFeatureQuietly(docFactory, XMLConstants.FEATURE_SECURE_PROCESSING, true)
XmlUtil.setFeatureQuietly(docFactory, "http://apache.org/xml/features/disallow-doctype-decl", true)
def transformerFactory = TransformerFactory.newInstance()
XmlUtil.setFeatureQuietly(transformerFactory, XMLConstants.FEATURE_SECURE_PROCESSING, true)
// Serialize with DOCTYPE control
String xmlWithDoctype = '''<?xml version="1.0"?>
<!DOCTYPE root SYSTEM "test.dtd">
<root><item>data</item></root>'''
// Serialize without allowing DOCTYPE
String safeXml = XmlUtil.serialize(xmlWithDoctype, false) // DOCTYPE removed
String unsafeXml = XmlUtil.serialize(xmlWithDoctype, true) // DOCTYPE preserved
// Working with Writable objects
def markupBuilder = new StreamingMarkupBuilder()
def writable = markupBuilder.bind {
catalog {
book(id: "1", "Sample Book")
}
}
String writableXml = XmlUtil.serialize(writable)
println writableXml
// Batch processing with utilities
def xmlFiles = new File("xml-data").listFiles { it.name.endsWith(".xml") }
xmlFiles.each { file ->
def content = file.text
def formatted = XmlUtil.serialize(content)
def outputFile = new File("formatted/${file.name}")
outputFile.text = formatted
println "Formatted: ${file.name}"
}Specialized printer for groovy.util.Node objects with extensive formatting control.
/**
* Default constructor writing to System.out
*/
XmlNodePrinter()
/**
* Constructor with PrintWriter output
* @param out - PrintWriter for output
*/
XmlNodePrinter(PrintWriter out)
/**
* Constructor with custom indentation
* @param out - PrintWriter for output
* @param indent - Indentation string
*/
XmlNodePrinter(PrintWriter out, String indent)
/**
* Constructor with indentation and quote style
* @param out - PrintWriter for output
* @param indent - Indentation string
* @param quote - Quote character for attributes
*/
XmlNodePrinter(PrintWriter out, String indent, String quote)
/**
* Constructor with IndentPrinter
* @param out - IndentPrinter for formatted output
*/
XmlNodePrinter(IndentPrinter out)
/**
* Constructor with IndentPrinter and quote style
* @param out - IndentPrinter for formatted output
* @param quote - Quote character for attributes
*/
XmlNodePrinter(IndentPrinter out, String quote)
/**
* Print Node to configured output
* @param node - Node to print
*/
void print(Node node)/**
* Control namespace awareness in output
* @param namespaceAware - true for namespace-aware printing
*/
void setNamespaceAware(boolean namespaceAware)
boolean isNamespaceAware()
/**
* Control whitespace preservation
* @param preserveWhitespace - true to preserve whitespace
*/
void setPreserveWhitespace(boolean preserveWhitespace)
boolean isPreserveWhitespace()
/**
* Set quote character for attributes
* @param quote - Quote character (" or ')
*/
void setQuote(String quote)
String getQuote()
/**
* Control empty element formatting
* @param expandEmptyElements - true to expand empty elements
*/
void setExpandEmptyElements(boolean expandEmptyElements)
boolean isExpandEmptyElements()Usage Examples:
import groovy.xml.*
import groovy.util.IndentPrinter
// Create Node to print
def parser = new XmlParser()
def node = parser.parseText('''
<library>
<book id="1" title="Groovy Programming"/>
<book id="2" title="XML Processing">
<author>Jane Doe</author>
<categories>
<category>XML</category>
<category>Programming</category>
</categories>
</book>
</library>
''')
// Basic printing to System.out
def printer = new XmlNodePrinter()
printer.print(node)
// Print to StringWriter with custom formatting
def writer = new StringWriter()
def customPrinter = new XmlNodePrinter(new PrintWriter(writer), " ", '"')
customPrinter.setNamespaceAware(true)
customPrinter.setExpandEmptyElements(true)
customPrinter.setPreserveWhitespace(false)
customPrinter.print(node)
println writer.toString()
// Print to file with IndentPrinter
new File("formatted-output.xml").withWriter { fileWriter ->
def indentPrinter = new IndentPrinter(fileWriter, " ")
def filePrinter = new XmlNodePrinter(indentPrinter, "'")
filePrinter.print(node)
}
// Configuration examples
printer.setQuote("'") // Use single quotes
printer.setExpandEmptyElements(true) // <empty></empty> instead of <empty/>
printer.setNamespaceAware(true) // Handle namespaces properly
printer.setPreserveWhitespace(true) // Keep original whitespaceUtility methods for creating properly configured XML factory instances with security settings.
/**
* Create secure DocumentBuilderFactory
* @return Configured DocumentBuilderFactory
*/
static DocumentBuilderFactory createDocumentBuilderFactory()
/**
* Create secure SAXParserFactory
* @return Configured SAXParserFactory
*/
static SAXParserFactory createSaxParserFactory()Usage Examples:
import groovy.xml.FactorySupport
// Create secure factories
def docBuilderFactory = FactorySupport.createDocumentBuilderFactory()
def saxParserFactory = FactorySupport.createSaxParserFactory()
// Use factories for secure parsing
def docBuilder = docBuilderFactory.newDocumentBuilder()
def saxParser = saxParserFactory.newSAXParser()
// These factories are preconfigured with security features
def doc = docBuilder.parse(new File("input.xml"))Install with Tessl CLI
npx tessl i tessl/maven-org-apache-groovy--groovy-xml