Top Description Fields Constructors Methods
groovy.xml

public Class XmlSlurper

extends DefaultHandler
Class Inheritance
Imports
groovy.namespace.QName, groovy.xml.slurpersupport.GPathResult, .NamespaceAwareHashMap, .Node, .NodeChild, org.xml.sax.Attributes, .DTDHandler, .EntityResolver, .ErrorHandler, .InputSource, .SAXException, .SAXNotRecognizedException, .SAXNotSupportedException, .XMLReader, org.xml.sax.helpers.DefaultHandler, javax.xml.XMLConstants, javax.xml.parsers.ParserConfigurationException, .SAXParser, .SAXParserFactory, java.io.File, .FileInputStream, .IOException, .InputStream, .Reader, .StringReader, java.net.URL, java.nio.file.Files, .Path, java.util.HashMap, .Map, .Stack

Parse XML into a document tree that may be traversed similar to XPath expressions. For example:
import groovy.xml.XmlSlurper
def rootNode = new XmlSlurper().parseText(
   '<root><one a1="uno!"/><two>Some text!</two></root>' )

assert rootNode.name() == 'root'
assert rootNode.one[0].@a1 == 'uno!'
assert rootNode.two.text() == 'Some text!'
rootNode.children().each { assert it.name() in ['one','two'] }

Note that in some cases, a 'selector' expression may not resolve to a single node. For example:

import groovy.xml.XmlSlurper
def rootNode = new XmlSlurper().parseText(
   '''<root>
        <a>one!</a>
        <a>two!</a>
      </root>''' )

assert rootNode.a.size() == 2
rootNode.a.each { assert it.text() in ['one!','two!'] }
See Also
GPathResult

Field Summary

Modifier and TypeField and Description
private final StringBuilder
private Node
private boolean
private boolean
private final Map<String, String>
private final XMLReader
private final Stack<Node>

Constructor Summary

AccessConstructor and Description
public
XmlSlurper()

Creates a non-validating and namespace-aware XmlSlurper which does not allow DOCTYPE declarations in documents.

public
XmlSlurper(final boolean
true if the parser should validate documents as they are parsed; false otherwise.
validating
,
final boolean
true if the parser should provide support for XML namespaces; false otherwise.
namespaceAware
)

Creates a XmlSlurper which does not allow DOCTYPE declarations in documents.

public
XmlSlurper(final boolean
true if the parser should validate documents as they are parsed; false otherwise.
validating
,
final boolean
true if the parser should provide support for XML namespaces; false otherwise.
namespaceAware
,
boolean
true if the parser should provide support for DOCTYPE declarations; false otherwise.
allowDocTypeDeclaration
)

Creates a XmlSlurper.

public
XmlSlurper(final XMLReader reader)

public
XmlSlurper(final SAXParser parser)

Method Summary

Modifier and TypeMethod and Description
private void
public void
characters(final char[]
The characters.
ch
,
final int
The start position in the character array.
start
,
final int
The number of characters to use from the character array.
length
)

Overrides org.xml.sax.helpers.DefaultHandler.characters.

Implements org.xml.sax.ContentHandler.characters.

Receive notification of character data inside an element.
public void
endDocument()

Overrides org.xml.sax.helpers.DefaultHandler.endDocument.

Implements org.xml.sax.ContentHandler.endDocument.

Receive notification of the end of the document.
public void
endElement(final String
The Namespace URI, or the empty string if the element has no Namespace URI or if Namespace processing is not being performed.
namespaceURI
,
final String
The local name (without prefix), or the empty string if Namespace processing is not being performed.
localName
,
final String
The qualified name (with prefix), or the empty string if qualified names are not available.
qName
)

Overrides org.xml.sax.helpers.DefaultHandler.endElement.

Implements org.xml.sax.ContentHandler.endElement.

Receive notification of the end of an element.
public GPathResult

Returns:

The GPathResult instance created by consuming a stream of SAX events Note if one of the parse methods has been called then this returns null Note if this is called more than once all calls after the first will return null
getDocument
()

public DTDHandler
public EntityResolver
public ErrorHandler
public boolean
getFeature(final String uri)

public Object
getProperty(final String uri)

public void
ignorableWhitespace(char[]
The whitespace characters.
buffer
,
int
The start position in the character array.
start
,
int
The number of characters to use from the character array.
len
)

Overrides org.xml.sax.helpers.DefaultHandler.ignorableWhitespace.

Implements org.xml.sax.ContentHandler.ignorableWhitespace.

Receive notification of ignorable whitespace in element content.
public boolean

Returns:

true if ignorable whitespace is kept
isKeepIgnorableWhitespace
()

public GPathResult

Returns:

An object which supports GPath expressions
parse
(final InputSource
the InputSource to parse
input
)

Parse the content of the specified input source into a GPathResult object

public GPathResult

Returns:

An object which supports GPath expressions
parse
(final File
the File to parse
file
)

Parses the content of the given file as XML turning it into a GPathResult object

public GPathResult

Returns:

An object which supports GPath expressions
parse
(final InputStream
the InputStream to parse
input
)

Parse the content of the specified input stream into an GPathResult Object.

public GPathResult

Returns:

An object which supports GPath expressions
parse
(final Reader
the Reader to parse
in
)

Parse the content of the specified reader into a GPathResult Object.

public GPathResult

Returns:

An object which supports GPath expressions
parse
(final String
a String containing the URI to parse
uri
)

Parse the content of the specified URI into a GPathResult Object

public GPathResult
parse(final Path path)

public GPathResult

Returns:

An object which supports GPath expressions
parseText
(final String
a String containing XML to parse
text
)

A helper method to parse the given text as XML

public void
setDTDHandler(final DTDHandler dtdHandler)

public void
setEntityBaseUrl(final URL
The URL used to resolve relative URLs
base
)

Resolves entities against using the supplied URL as the base for relative URLs

public void
setEntityResolver(final EntityResolver entityResolver)

public void
setErrorHandler(final ErrorHandler errorHandler)

public void
setFeature(final String uri, final boolean value)

public void
setKeepIgnorableWhitespace(boolean
If true then ignorable whitespace (i.e. whitespace before elements) is kept. The default is to discard the whitespace.
keepIgnorableWhitespace
)

public void
setKeepWhitespace(boolean
If true then whitespace before elements is kept. The default is to discard the whitespace.
keepWhitespace
)

Deprecated use setKeepIgnorableWhitespace
public void
setProperty(final String uri, final Object value)

private static void
setQuietly(SAXParserFactory factory, String feature, boolean value)

public void
startDocument()

Overrides org.xml.sax.helpers.DefaultHandler.startDocument.

Implements org.xml.sax.ContentHandler.startDocument.

Receive notification of the beginning of the document.
public void
startElement(final String
The Namespace URI, or the empty string if the element has no Namespace URI or if Namespace processing is not being performed.
namespaceURI
,
final String
The local name (without prefix), or the empty string if Namespace processing is not being performed.
localName
,
final String
The qualified name (with prefix), or the empty string if qualified names are not available.
qName
,
final Attributes
The attributes attached to the element. If there are no attributes, it shall be an empty Attributes object.
atts
)

Overrides org.xml.sax.helpers.DefaultHandler.startElement.

Implements org.xml.sax.ContentHandler.startElement.

Receive notification of the start of an element.
public void
startPrefixMapping(final String
The Namespace prefix being declared.
tag
,
final String
The Namespace URI mapped to the prefix.
uri
)

Overrides org.xml.sax.helpers.DefaultHandler.startPrefixMapping.

Implements org.xml.sax.ContentHandler.startPrefixMapping.

Receive notification of the start of a Namespace mapping.
Inherited from org.xml.sax.helpers.DefaultHandler:
endPrefixMappingerrorfatalErrornotationDeclprocessingInstructionresolveEntitysetDocumentLocatorskippedEntityunparsedEntityDeclwarning

Field Detail

charBufferback to summary
private final StringBuilder charBuffer
currentNodeback to summary
private Node currentNode
keepIgnorableWhitespaceback to summary
private boolean keepIgnorableWhitespace
namespaceAwareback to summary
private boolean namespaceAware
namespaceTagHintsback to summary
private final Map<String, String> namespaceTagHints
readerback to summary
private final XMLReader reader
stackback to summary
private final Stack<Node> stack

Constructor Detail

XmlSlurperback to summary
public XmlSlurper() throws ParserConfigurationException, SAXException

Creates a non-validating and namespace-aware XmlSlurper which does not allow DOCTYPE declarations in documents.

Exceptions
ParserConfigurationException:
if no parser which satisfies the requested configuration can be created.
SAXException:
for SAX errors.
XmlSlurperback to summary
public XmlSlurper(final boolean validating, final boolean namespaceAware) throws ParserConfigurationException, SAXException

Creates a XmlSlurper which does not allow DOCTYPE declarations in documents.

Parameters
validating:boolean

true if the parser should validate documents as they are parsed; false otherwise.

namespaceAware:boolean

true if the parser should provide support for XML namespaces; false otherwise.

Exceptions
ParserConfigurationException:
if no parser which satisfies the requested configuration can be created.
SAXException:
for SAX errors.
XmlSlurperback to summary
public XmlSlurper(final boolean validating, final boolean namespaceAware, boolean allowDocTypeDeclaration) throws ParserConfigurationException, SAXException

Creates a XmlSlurper.

Parameters
validating:boolean

true if the parser should validate documents as they are parsed; false otherwise.

namespaceAware:boolean

true if the parser should provide support for XML namespaces; false otherwise.

allowDocTypeDeclaration:boolean

true if the parser should provide support for DOCTYPE declarations; false otherwise.

Exceptions
ParserConfigurationException:
if no parser which satisfies the requested configuration can be created.
SAXException:
for SAX errors.
XmlSlurperback to summary
public XmlSlurper(final XMLReader reader)
XmlSlurperback to summary
public XmlSlurper(final SAXParser parser) throws SAXException

Method Detail

addCdataback to summary
private void addCdata()
charactersback to summary
public void characters(final char[] ch, final int start, final int length) throws SAXException

Overrides org.xml.sax.helpers.DefaultHandler.characters.

Implements org.xml.sax.ContentHandler.characters.

Doc from org.xml.sax.helpers.DefaultHandler.characters.

Receive notification of character data inside an element.

By default, do nothing. Application writers may override this method to take specific actions for each chunk of character data (such as adding the data to a node or buffer, or printing it to a file).

Parameters
ch:char[]

The characters.

start:int

The start position in the character array.

length:int

The number of characters to use from the character array.

Exceptions
SAXException:
Any SAX exception, possibly wrapping another exception.
endDocumentback to summary
public void endDocument() throws SAXException

Overrides org.xml.sax.helpers.DefaultHandler.endDocument.

Implements org.xml.sax.ContentHandler.endDocument.

Doc from org.xml.sax.helpers.DefaultHandler.endDocument.

Receive notification of the end of the document.

By default, do nothing. Application writers may override this method in a subclass to take specific actions at the end of a document (such as finalising a tree or closing an output file).

Exceptions
SAXException:
Any SAX exception, possibly wrapping another exception.
endElementback to summary
public void endElement(final String namespaceURI, final String localName, final String qName) throws SAXException

Overrides org.xml.sax.helpers.DefaultHandler.endElement.

Implements org.xml.sax.ContentHandler.endElement.

Doc from org.xml.sax.helpers.DefaultHandler.endElement.

Receive notification of the end of an element.

By default, do nothing. Application writers may override this method in a subclass to take specific actions at the end of each element (such as finalising a tree node or writing output to a file).

Parameters
namespaceURI:String

The Namespace URI, or the empty string if the element has no Namespace URI or if Namespace processing is not being performed.

localName:String

The local name (without prefix), or the empty string if Namespace processing is not being performed.

qName:String

The qualified name (with prefix), or the empty string if qualified names are not available.

Exceptions
SAXException:
Any SAX exception, possibly wrapping another exception.
getDocumentback to summary
public GPathResult getDocument()
Returns:GPathResult

The GPathResult instance created by consuming a stream of SAX events Note if one of the parse methods has been called then this returns null Note if this is called more than once all calls after the first will return null

getDTDHandlerback to summary
public DTDHandler getDTDHandler()
getEntityResolverback to summary
public EntityResolver getEntityResolver()
getErrorHandlerback to summary
public ErrorHandler getErrorHandler()
getFeatureback to summary
public boolean getFeature(final String uri) throws SAXNotRecognizedException, SAXNotSupportedException
getPropertyback to summary
public Object getProperty(final String uri) throws SAXNotRecognizedException, SAXNotSupportedException
ignorableWhitespaceback to summary
public void ignorableWhitespace(char[] buffer, int start, int len) throws SAXException

Overrides org.xml.sax.helpers.DefaultHandler.ignorableWhitespace.

Implements org.xml.sax.ContentHandler.ignorableWhitespace.

Doc from org.xml.sax.helpers.DefaultHandler.ignorableWhitespace.

Receive notification of ignorable whitespace in element content.

By default, do nothing. Application writers may override this method to take specific actions for each chunk of ignorable whitespace (such as adding data to a node or buffer, or printing it to a file).

Parameters
buffer:char[]

The whitespace characters.

start:int

The start position in the character array.

len:int

The number of characters to use from the character array.

Exceptions
SAXException:
Any SAX exception, possibly wrapping another exception.
isKeepIgnorableWhitespaceback to summary
public boolean isKeepIgnorableWhitespace()
Returns:boolean

true if ignorable whitespace is kept

parseback to summary
public GPathResult parse(final InputSource input) throws IOException, SAXException

Parse the content of the specified input source into a GPathResult object

Parameters
input:InputSource

the InputSource to parse

Returns:GPathResult

An object which supports GPath expressions

Exceptions
IOException:
An IO exception from the parser, possibly from a byte stream or character stream supplied by the application.
SAXException:
Any SAX exception, possibly wrapping another exception.
parseback to summary
public GPathResult parse(final File file) throws IOException, SAXException

Parses the content of the given file as XML turning it into a GPathResult object

Parameters
file:File

the File to parse

Returns:GPathResult

An object which supports GPath expressions

Exceptions
IOException:
An IO exception from the parser, possibly from a byte stream or character stream supplied by the application.
SAXException:
Any SAX exception, possibly wrapping another exception.
parseback to summary
public GPathResult parse(final InputStream input) throws IOException, SAXException

Parse the content of the specified input stream into an GPathResult Object. Note that using this method will not provide the parser with any URI for which to find DTDs etc. It is up to you to close the InputStream after parsing is complete (if required).

Parameters
input:InputStream

the InputStream to parse

Returns:GPathResult

An object which supports GPath expressions

Exceptions
IOException:
An IO exception from the parser, possibly from a byte stream or character stream supplied by the application.
SAXException:
Any SAX exception, possibly wrapping another exception.
parseback to summary
public GPathResult parse(final Reader in) throws IOException, SAXException

Parse the content of the specified reader into a GPathResult Object. Note that using this method will not provide the parser with any URI for which to find DTDs etc. It is up to you to close the Reader after parsing is complete (if required).

Parameters
in:Reader

the Reader to parse

Returns:GPathResult

An object which supports GPath expressions

Exceptions
IOException:
An IO exception from the parser, possibly from a byte stream or character stream supplied by the application.
SAXException:
Any SAX exception, possibly wrapping another exception.
parseback to summary
public GPathResult parse(final String uri) throws IOException, SAXException

Parse the content of the specified URI into a GPathResult Object

Parameters
uri:String

a String containing the URI to parse

Returns:GPathResult

An object which supports GPath expressions

Exceptions
IOException:
An IO exception from the parser, possibly from a byte stream or character stream supplied by the application.
SAXException:
Any SAX exception, possibly wrapping another exception.
parseback to summary
public GPathResult parse(final Path path) throws IOException, SAXException
parseTextback to summary
public GPathResult parseText(final String text) throws IOException, SAXException

A helper method to parse the given text as XML

Parameters
text:String

a String containing XML to parse

Returns:GPathResult

An object which supports GPath expressions

Exceptions
IOException:
An IO exception from the parser, possibly from a byte stream or character stream supplied by the application.
SAXException:
Any SAX exception, possibly wrapping another exception.
setDTDHandlerback to summary
public void setDTDHandler(final DTDHandler dtdHandler)
setEntityBaseUrlback to summary
public void setEntityBaseUrl(final URL base)

Resolves entities against using the supplied URL as the base for relative URLs

Parameters
base:URL

The URL used to resolve relative URLs

setEntityResolverback to summary
public void setEntityResolver(final EntityResolver entityResolver)
setErrorHandlerback to summary
public void setErrorHandler(final ErrorHandler errorHandler)
setFeatureback to summary
public void setFeature(final String uri, final boolean value) throws SAXNotRecognizedException, SAXNotSupportedException
setKeepIgnorableWhitespaceback to summary
public void setKeepIgnorableWhitespace(boolean keepIgnorableWhitespace)
Parameters
keepIgnorableWhitespace:boolean

If true then ignorable whitespace (i.e. whitespace before elements) is kept. The default is to discard the whitespace.

setKeepWhitespaceback to summary
public void setKeepWhitespace(boolean keepWhitespace)

Deprecated

use setKeepIgnorableWhitespace

Parameters
keepWhitespace:boolean

If true then whitespace before elements is kept. The default is to discard the whitespace.

Annotations
@Deprecated
setPropertyback to summary
public void setProperty(final String uri, final Object value) throws SAXNotRecognizedException, SAXNotSupportedException
setQuietlyback to summary
private static void setQuietly(SAXParserFactory factory, String feature, boolean value)
startDocumentback to summary
public void startDocument() throws SAXException

Overrides org.xml.sax.helpers.DefaultHandler.startDocument.

Implements org.xml.sax.ContentHandler.startDocument.

Doc from org.xml.sax.helpers.DefaultHandler.startDocument.

Receive notification of the beginning of the document.

By default, do nothing. Application writers may override this method in a subclass to take specific actions at the beginning of a document (such as allocating the root node of a tree or creating an output file).

Exceptions
SAXException:
Any SAX exception, possibly wrapping another exception.
startElementback to summary
public void startElement(final String namespaceURI, final String localName, final String qName, final Attributes atts) throws SAXException

Overrides org.xml.sax.helpers.DefaultHandler.startElement.

Implements org.xml.sax.ContentHandler.startElement.

Doc from org.xml.sax.helpers.DefaultHandler.startElement.

Receive notification of the start of an element.

By default, do nothing. Application writers may override this method in a subclass to take specific actions at the start of each element (such as allocating a new tree node or writing output to a file).

Parameters
namespaceURI:String

The Namespace URI, or the empty string if the element has no Namespace URI or if Namespace processing is not being performed.

localName:String

The local name (without prefix), or the empty string if Namespace processing is not being performed.

qName:String

The qualified name (with prefix), or the empty string if qualified names are not available.

atts:Attributes

The attributes attached to the element. If there are no attributes, it shall be an empty Attributes object.

Exceptions
SAXException:
Any SAX exception, possibly wrapping another exception.
startPrefixMappingback to summary
public void startPrefixMapping(final String tag, final String uri) throws SAXException

Overrides org.xml.sax.helpers.DefaultHandler.startPrefixMapping.

Implements org.xml.sax.ContentHandler.startPrefixMapping.

Doc from org.xml.sax.helpers.DefaultHandler.startPrefixMapping.

Receive notification of the start of a Namespace mapping.

By default, do nothing. Application writers may override this method in a subclass to take specific actions at the start of each Namespace prefix scope (such as storing the prefix mapping).

Parameters
tag:String

The Namespace prefix being declared.

uri:String

The Namespace URI mapped to the prefix.

Exceptions
SAXException:
Any SAX exception, possibly wrapping another exception.