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
—
Comprehensive XML building capabilities including markup builders for formatted output, DOM builders for W3C DOM integration, and streaming builders for memory-efficient large document generation.
A powerful builder for creating XML and HTML markup with sophisticated formatting options and helper utilities. Extends Groovy's BuilderSupport to provide a DSL approach to XML generation.
/**
* Default constructor writing to System.out
*/
MarkupBuilder()
/**
* Constructor with PrintWriter output
* @param pw - PrintWriter for output
*/
MarkupBuilder(PrintWriter pw)
/**
* Constructor with Writer output
* @param writer - Writer for output
*/
MarkupBuilder(Writer writer)
/**
* Constructor with IndentPrinter for formatted output
* @param out - IndentPrinter for formatted output
*/
MarkupBuilder(IndentPrinter out)/**
* Control quote style for attributes
* @param useDoubleQuotes - true for double quotes, false for single
*/
void setDoubleQuotes(boolean useDoubleQuotes)
boolean getDoubleQuotes()
/**
* Control handling of null attribute values
* @param omitNullAttributes - true to omit null valued attributes
*/
void setOmitNullAttributes(boolean omitNullAttributes)
boolean isOmitNullAttributes()
/**
* Control handling of empty attribute values
* @param omitEmptyAttributes - true to omit empty string attributes
*/
void setOmitEmptyAttributes(boolean omitEmptyAttributes)
boolean isOmitEmptyAttributes()
/**
* Control empty element formatting
* @param expandEmptyElements - true to expand empty elements with closing tags
*/
void setExpandEmptyElements(boolean expandEmptyElements)
boolean isExpandEmptyElements()
/**
* Control attribute value escaping
* @param escapeAttributes - true to escape attribute values
*/
void setEscapeAttributes(boolean escapeAttributes)
boolean isEscapeAttributes()
/**
* Get markup helper for advanced operations
* @return MarkupBuilderHelper instance
*/
MarkupBuilderHelper getMkp()
/**
* Set additional character filters for text content
* @param additionalFilters - List of character filter functions
*/
void setAdditionalFilters(List<Function<Character, Optional<String>>> additionalFilters)
/**
* Get additional character filters
* @return List of character filter functions
*/
List<Function<Character, Optional<String>>> getAdditionalFilters()
/**
* Get the underlying printer used for output
* @return IndentPrinter instance
*/
IndentPrinter getPrinter()/**
* Character filtering options for MarkupBuilder
*/
enum CharFilter {
/** Strict XML character filtering */
XML_STRICT,
/** Filter all XML-related characters */
XML_ALL,
/** No character filtering */
NONE
}Usage Examples:
import groovy.xml.MarkupBuilder
// Basic XML generation
def writer = new StringWriter()
def xml = new MarkupBuilder(writer)
xml.books {
book(id: "1", title: "Groovy in Action") {
author("Dierk König")
price("49.99")
description {
mkp.yield("Comprehensive guide to ")
mkp.yieldUnescaped("<em>Groovy</em>")
mkp.yield(" programming")
}
}
book(id: "2", title: "Programming Groovy") {
author("Venkat Subramaniam")
price("45.99")
}
}
println writer.toString()
// Configuration example
def configuredXml = new MarkupBuilder(new StringWriter())
configuredXml.setDoubleQuotes(true)
configuredXml.setExpandEmptyElements(true)
configuredXml.setOmitNullAttributes(true)
configuredXml.catalog {
item(id: "123", category: null, title: "Sample") // category omitted
emptyItem() // Expanded as <emptyItem></emptyItem>
}
// Namespace example
xml.html("xmlns": "http://www.w3.org/1999/xhtml") {
head {
title("Sample Page")
}
body {
h1("Welcome")
p("This is a sample XHTML document")
}
}Helper class providing advanced markup operations including raw content insertion, comments, and XML declarations.
/**
* Constructor (typically accessed via MarkupBuilder.getMkp())
* @param builder - Parent MarkupBuilder
*/
MarkupBuilderHelper(MarkupBuilder builder)
/**
* Yield escaped content
* @param value - Content to yield with escaping
*/
void yield(Object value)
void yield(String value)
/**
* Yield unescaped raw content
* @param value - Raw content to yield without escaping
*/
void yieldUnescaped(Object value)
void yieldUnescaped(String value)
/**
* Add XML comment
* @param value - Comment text
*/
void comment(String value)
/**
* Add XML declaration
* @param args - Declaration attributes (version, encoding, standalone)
*/
void xmlDeclaration(Map<String, Object> args)
/**
* Add processing instruction
* @param args - Map with PI target as key and attributes as value
*/
void pi(Map<String, Map<String, Object>> args)Usage Examples:
def writer = new StringWriter()
def xml = new MarkupBuilder(writer)
xml.document {
mkp.xmlDeclaration(version: "1.0", encoding: "UTF-8")
mkp.comment("Generated by Groovy XML")
root {
content {
mkp.yield("Safe content: ")
mkp.yield("<script>alert('safe')</script>") // Escaped
mkp.yieldUnescaped("<strong>Bold text</strong>") // Raw HTML
}
mkp.pi("xml-stylesheet": [type: "text/xsl", href: "style.xsl"])
}
}Builder for creating W3C DOM Document objects, providing integration with standard Java XML DOM APIs.
/**
* Constructor with existing Document
* @param document - DOM Document to build upon
*/
DOMBuilder(Document document)
/**
* Constructor with DocumentBuilder
* @param documentBuilder - DocumentBuilder for document creation
*/
DOMBuilder(DocumentBuilder documentBuilder)
/**
* Create new DOMBuilder instance with default settings
* @return New DOMBuilder instance
*/
static DOMBuilder newInstance()
/**
* Create DOMBuilder with validation and namespace control
* @param validating - Enable DTD validation
* @param namespaceAware - Enable namespace processing
* @return New DOMBuilder instance
*/
static DOMBuilder newInstance(boolean validating, boolean namespaceAware)
/**
* Parse XML text into DOM Document
* @param text - XML text to parse
* @return DOM Document
*/
Document parseText(String text)/**
* Parse XML from Reader into DOM Document
* @param reader - Reader containing XML
* @return DOM Document
*/
static Document parse(Reader reader)
/**
* Parse with validation and namespace control
* @param reader - Reader containing XML
* @param validating - Enable DTD validation
* @param namespaceAware - Enable namespace processing
* @return DOM Document
*/
static Document parse(Reader reader, boolean validating, boolean namespaceAware)
/**
* Parse with full control over processing
* @param reader - Reader containing XML
* @param validating - Enable DTD validation
* @param namespaceAware - Enable namespace processing
* @param allowDocTypeDeclaration - Allow DOCTYPE declarations
* @return DOM Document
*/
static Document parse(Reader reader, boolean validating, boolean namespaceAware, boolean allowDocTypeDeclaration)Usage Examples:
import groovy.xml.DOMBuilder
import org.w3c.dom.Document
// Create DOM using builder DSL
def builder = DOMBuilder.newInstance()
Document doc = builder.books {
book(id: "1") {
title("Groovy Programming")
author("John Doe")
}
book(id: "2") {
title("XML Processing")
author("Jane Smith")
}
}
// Access DOM elements
println doc.documentElement.tagName // "books"
def books = doc.getElementsByTagName("book")
println books.length // 2
// Parse existing XML into DOM
def xmlText = '<catalog><item>Sample</item></catalog>'
Document parsedDoc = builder.parseText(xmlText)
// Static parsing
Document staticDoc = DOMBuilder.parse(new StringReader(xmlText))
// Namespace-aware DOM building
def nsBuilder = DOMBuilder.newInstance(false, true)
Document nsDoc = nsBuilder.catalog("xmlns:lib": "http://library.org") {
"lib:book"(isbn: "123") {
"lib:title"("Advanced XML")
}
}Memory-efficient builder for generating large XML documents using streaming output. Ideal for generating XML that doesn't fit in memory or when processing large datasets.
/**
* Default constructor
*/
StreamingMarkupBuilder()
/**
* Bind closure to create streamable markup
* @param closure - Closure defining markup structure
* @return Writable object for streaming output
*/
def bind(Closure closure)
/**
* Bind Node object to create streamable markup
* @param node - Node to convert to streaming markup
* @return Writable object for streaming output
*/
def bindNode(Node node)/**
* Control quote style (default: false for single quotes)
*/
boolean useDoubleQuotes
/**
* Control empty element expansion (default: false)
*/
boolean expandEmptyElements
/**
* Set output encoding (default: null for platform default)
*/
def encodingUsage Examples:
import groovy.xml.StreamingMarkupBuilder
// Basic streaming markup
def builder = new StreamingMarkupBuilder()
def markup = builder.bind {
catalog {
(1..1000).each { i ->
book(id: i) {
title("Book ${i}")
price(Math.random() * 100)
}
}
}
}
// Write to file efficiently
new File("large-catalog.xml").withWriter { writer ->
markup.writeTo(writer)
}
// Configuration
builder.useDoubleQuotes = true
builder.expandEmptyElements = true
builder.encoding = "UTF-8"
// Streaming with XML declaration
def markupWithDecl = builder.bind {
mkp.xmlDeclaration(version: "1.0", encoding: "UTF-8")
mkp.comment("Generated streaming XML")
data {
records {
(1..10000).each { i ->
record(id: i, timestamp: new Date()) {
value(Math.random())
}
}
}
}
}
// Stream to OutputStream
new FileOutputStream("data.xml").withStream { stream ->
markupWithDecl.writeTo(new OutputStreamWriter(stream, "UTF-8"))
}
// Convert existing Node to streaming
def parser = new XmlParser()
def existingNode = parser.parseText('<sample><item>test</item></sample>')
def streamableNode = builder.bindNode(existingNode)
println streamableNode.toString()/**
* Builder using StAX XMLStreamWriter
* @param xmlStreamWriter - StAX XMLStreamWriter for output
*/
StaxBuilder(XMLStreamWriter xmlStreamWriter)/**
* Builder generating SAX events
* @param handler - ContentHandler for SAX events
*/
SAXBuilder(ContentHandler handler)// Streaming builders extending AbstractStreamingBuilder
class StreamingDOMBuilder extends AbstractStreamingBuilder
class StreamingSAXBuilder extends AbstractStreamingBuilderUsage Examples:
import groovy.xml.*
import javax.xml.stream.XMLOutputFactory
import javax.xml.transform.stream.StreamResult
// StAX builder example
def outputFactory = XMLOutputFactory.newInstance()
def stringWriter = new StringWriter()
def streamWriter = outputFactory.createXMLStreamWriter(stringWriter)
def staxBuilder = new StaxBuilder(streamWriter)
staxBuilder.library {
book(title: "StAX Processing") {
author("XML Expert")
}
}
streamWriter.close()
println stringWriter.toString()
// SAX builder example
def handler = new DefaultHandler() {
void startElement(String uri, String localName, String qName, Attributes attributes) {
println "Start: $qName"
}
}
def saxBuilder = new SAXBuilder(handler)
saxBuilder.catalog {
item("Test Item")
}Provides comprehensive XML entity constants for use in XML generation, offering all standard HTML and XML entities as static final constants.
/**
* Constructor with entity name
* @param name - Entity name as string
*/
Entity(String name)
/**
* Constructor with entity code
* @param code - Entity code as integer
*/
Entity(int code)// Common entities
static final Entity nbsp, iexcl, cent, pound, curren, yen, brvbar, sect, uml, copy
static final Entity ordf, laquo, not, shy, reg, macr, deg, plusmn, sup2, sup3
static final Entity acute, micro, para, middot, cedil, sup1, ordm, raquo
static final Entity frac14, frac12, frac34, iquest
// Latin characters (uppercase)
static final Entity Agrave, Aacute, Acirc, Atilde, Auml, Aring, AElig, Ccedil
static final Entity Egrave, Eacute, Ecirc, Euml, Igrave, Iacute, Icirc, Iuml
static final Entity ETH, Ntilde, Ograve, Oacute, Ocirc, Otilde, Ouml, times
static final Entity Oslash, Ugrave, Uacute, Ucirc, Uuml, Yacute, THORN
// Latin characters (lowercase)
static final Entity szlig, agrave, aacute, acirc, atilde, auml, aring, aelig, ccedil
static final Entity egrave, eacute, ecirc, euml, igrave, iacute, icirc, iuml
static final Entity eth, ntilde, ograve, oacute, ocirc, otilde, ouml, divide
static final Entity oslash, ugrave, uacute, ucirc, uuml, yacute, thorn, yuml
// Special characters
static final Entity lt, gt, amp, apos, quot, OElig, oelig, Scaron, scaron, Yuml
static final Entity circ, tilde, ensp, emsp, thinsp, zwnj, zwj, lrm, rlm
static final Entity ndash, mdash, lsquo, rsquo, sbquo, ldquo, rdquo, bdquo
static final Entity dagger, Dagger, permil, lsaquo, rsaquo, euroUsage Examples:
import groovy.xml.MarkupBuilder
import groovy.xml.Entity
// Using entities in markup generation
def writer = new StringWriter()
def xml = new MarkupBuilder(writer)
xml.document {
title("Price: ${Entity.pound}25.99") // Price: £25.99
content {
p("Copyright ${Entity.copy} 2023") // Copyright © 2023
p("Temperature: 25${Entity.deg}C") // Temperature: 25°C
quote("${Entity.ldquo}Hello World${Entity.rdquo}") // "Hello World"
}
math {
formula("x${Entity.sup2} + y${Entity.sup2} = z${Entity.sup2}") // x² + y² = z²
fraction("${Entity.frac12} + ${Entity.frac14} = ${Entity.frac34}") // ½ + ¼ = ¾
}
}
println writer.toString()
// Using entities for safe XML generation
xml.data {
comparison("5 ${Entity.lt} 10 ${Entity.amp} 10 ${Entity.gt} 5") // 5 < 10 & 10 > 5
quoted("He said ${Entity.quot}Hello${Entity.quot}") // He said "Hello"
}
// Custom entity usage
def customEntity = new Entity("custom")
def codeEntity = new Entity(8364) // Euro symbol by code
xml.custom {
field(customEntity.toString())
symbol(codeEntity.toString())
}
// Build method for integration with builders
customEntity.build(xml) // Integrates entity with builderBuilder for generating SAX events directly, useful for integration with SAX-based processing chains.
/**
* Constructor with ContentHandler for SAX events
* @param handler - ContentHandler to receive SAX events
*/
SAXBuilder(ContentHandler handler)Builder using StAX XMLStreamWriter for efficient streaming XML generation.
/**
* Constructor with XMLStreamWriter
* @param xmlStreamWriter - StAX XMLStreamWriter for output
*/
StaxBuilder(XMLStreamWriter xmlStreamWriter)Advanced streaming builders extending AbstractStreamingBuilder for specialized streaming scenarios.
/**
* Streaming DOM builder for large document generation
*/
class StreamingDOMBuilder extends AbstractStreamingBuilder
/**
* Streaming SAX builder for event-based generation
*/
class StreamingSAXBuilder extends AbstractStreamingBuilderUsage Examples:
import groovy.xml.*
import javax.xml.stream.XMLOutputFactory
import javax.xml.transform.sax.SAXResult
import org.xml.sax.helpers.DefaultHandler
// StAX builder example
def outputFactory = XMLOutputFactory.newInstance()
def stringWriter = new StringWriter()
def streamWriter = outputFactory.createXMLStreamWriter(stringWriter)
def staxBuilder = new StaxBuilder(streamWriter)
staxBuilder.library {
book(title: "StAX Processing") {
author("XML Expert")
chapters {
chapter(number: "1", "Introduction to StAX")
chapter(number: "2", "Advanced StAX Features")
}
}
}
streamWriter.close()
println stringWriter.toString()
// SAX builder example
def handler = new DefaultHandler() {
void startElement(String uri, String localName, String qName, Attributes attributes) {
println "Start element: $qName"
if (attributes.length > 0) {
for (int i = 0; i < attributes.length; i++) {
println " Attribute: ${attributes.getQName(i)} = ${attributes.getValue(i)}"
}
}
}
void endElement(String uri, String localName, String qName) {
println "End element: $qName"
}
void characters(char[] ch, int start, int length) {
def text = new String(ch, start, length).trim()
if (text) {
println "Text content: $text"
}
}
}
def saxBuilder = new SAXBuilder(handler)
saxBuilder.catalog {
item(id: "1", "First Item")
item(id: "2", "Second Item")
}Install with Tessl CLI
npx tessl i tessl/maven-org-apache-groovy--groovy-xml