Package: groovy.xml

## [Java] Class XmlSlurper

- groovy.xml.XmlSlurper

-     public class XmlSlurper
      extends DefaultHandler

  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!'] }

  A more realistic example — a book catalog. Given this XML:

      <catalog>
        <book id="b1">
          <title>Programming Groovy 3</title>
          <author>Venkat Subramaniam</author>
          <year>2024</year>
        </book>
        <book id="b2">
          <title>Groovy in Action</title>
          <author>Dierk Koenig</author>
          <year>2015</year>
        </book>
      </catalog>

  the equivalent Groovy to slurp it and navigate the tree:

      def catalog = new XmlSlurper().parseText(xml)
      assert catalog.book.size() == 2
      assert catalog.book[0].title.text() == 'Programming Groovy 3'
      catalog.book.findAll { it.year.text().toInteger() >= 2020 }.each { book ->
          println "${book.title} by ${book.author}"
      }

  Navigation through the returned GPathResult is lazy, so selectors are evaluated on demand rather than exposing an eager `groovy.util.Node` tree.
  See Also:
    GPathResult

- - ### Constructor Summary

    Constructors
    Constructor and description
    `XmlSlurper()` Creates a non-validating and namespace-aware `XmlSlurper` which does not allow DOCTYPE declarations in documents.
    `XmlSlurper(boolean validating, boolean namespaceAware)` Creates a `XmlSlurper` which does not allow DOCTYPE declarations in documents.
    `XmlSlurper(boolean validating, boolean namespaceAware, boolean allowDocTypeDeclaration)` Creates a `XmlSlurper`.
    `XmlSlurper(XMLReader reader)` Creates a slurper backed by the supplied SAX reader.
    `XmlSlurper(SAXParser parser)` Creates a slurper backed by the supplied SAX parser.

  - ### Methods Summary

    Methods
    Type Params | Return Type | Name and description
    --- | --- | ---
    `` | `public void` | `characters(char[] ch, int start, int length)` Buffers character data until the surrounding element boundary is reached.
    `` | `public void` | `endDocument()` Receives the end-of-document callback.
    `` | `public void` | `endElement(String namespaceURI, String localName, String qName)` Flushes buffered text and restores the parent node when an end tag is reached.
    `` | `public DTDHandler` | `getDTDHandler()` Returns the SAX DTD handler configured on the underlying reader.
    `` | `public GPathResult` | `getDocument()` 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
    `` | `public EntityResolver` | `getEntityResolver()` Returns the SAX entity resolver configured on the underlying reader.
    `` | `public ErrorHandler` | `getErrorHandler()` Returns the SAX error handler configured on the underlying reader.
    `` | `public boolean` | `getFeature(String uri)` Looks up a SAX feature on the underlying reader.
    `` | `public Object` | `getProperty(String uri)` Looks up a SAX property on the underlying reader.
    `` | `public void` | `ignorableWhitespace(char[] buffer, int start, int len)` Receives ignorable whitespace and optionally preserves it as text content.
    `` | `public boolean` | `isAllowDocTypeDeclaration()` Determine if DOCTYPE declarations are allowed.
    `` | `public boolean` | `isKeepIgnorableWhitespace()` Returns: true if ignorable whitespace is kept
    `` | `public boolean` | `isNamespaceAware()` Determine if namespace handling is enabled.
    `` | `public boolean` | `isValidating()` Determine if the parser validates documents.
    `` | `public GPathResult` | `parse(InputSource input)` Parse the content of the specified input source into a GPathResult object
    `` | `public GPathResult` | `parse(File file)` Parses the content of the given file as XML turning it into a GPathResult object
    `` | `public GPathResult` | `parse(InputStream input)` Parse the content of the specified input stream into an GPathResult Object.
    `` | `public GPathResult` | `parse(Reader in)` Parse the content of the specified reader into a GPathResult Object.
    `` | `public GPathResult` | `parse(String uri)` Parse the content of the specified URI into a GPathResult Object
    `` | `public GPathResult` | `parse(Path path)` Parses the content of the file at the given path as XML turning it into a GPathResult object
    `` | `public GPathResult` | `parseText(String text)` A helper method to parse the given text as XML
    `` | `public void` | `setAllowDocTypeDeclaration(boolean allowDocTypeDeclaration)` Enable and/or disable DOCTYPE declaration support.
    `` | `public void` | `setDTDHandler(DTDHandler dtdHandler)` Sets the SAX DTD handler on the underlying reader.
    `` | `public void` | `setEntityBaseUrl(URL base)` Resolves entities against using the supplied URL as the base for relative URLs
    `` | `public void` | `setEntityResolver(EntityResolver entityResolver)` Sets the SAX entity resolver on the underlying reader.
    `` | `public void` | `setErrorHandler(ErrorHandler errorHandler)` Sets the SAX error handler on the underlying reader.
    `` | `public void` | `setFeature(String uri, boolean value)` Enables or disables a SAX feature on the underlying reader.
    `` | `public void` | `setKeepIgnorableWhitespace(boolean keepIgnorableWhitespace)` Parameters: `keepIgnorableWhitespace` - If true then ignorable whitespace (i.e. whitespace before elements) is kept.
    `` | `public void` | `setKeepWhitespace(boolean keepWhitespace)` deprecated: use setKeepIgnorableWhitespace
    `` | `public void` | `setNamespaceAware(boolean namespaceAware)` Enable and/or disable namespace handling.
    `` | `public void` | `setProperty(String uri, Object value)` Sets a SAX property on the underlying reader.
    `` | `public void` | `setValidating(boolean validating)` Enable and/or disable validation.
    `` | `public void` | `startDocument()` Resets the current slurped document before SAX events for a new parse begin.
    `` | `public void` | `startElement(String namespaceURI, String localName, String qName, Attributes atts)` Creates a slurper node for the current element and pushes it onto the parse stack.
    `` | `public void` | `startPrefixMapping(String tag, String uri)` Records namespace prefix hints for later GPathResult navigation.

  - ### Inherited Methods Summary

    Inherited Methods
    Methods inherited from class | Name
    --- | ---
    `class DefaultHandler` | `characters, declaration, endDocument, endElement, endPrefixMapping, equals, error, fatalError, getClass, hashCode, ignorableWhitespace, notationDecl, notify, notifyAll, processingInstruction, resolveEntity, setDocumentLocator, skippedEntity, startDocument, startElement, startPrefixMapping, toString, unparsedEntityDecl, wait, wait, wait, warning`

- - ### Constructor Detail

    - #### public XmlSlurper()

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

      Parser options can be configured via setters before the first parse call:

           // Using Groovy named parameters:
           def slurper = new XmlSlurper(namespaceAware: false, keepIgnorableWhitespace: true)

      throws:
        ParserConfigurationException if no parser which satisfies the requested configuration can be created.
      throws:
        SAXException for SAX errors.

    - #### public XmlSlurper(boolean validating, boolean namespaceAware)

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

      throws:
        ParserConfigurationException if no parser which satisfies the requested configuration can be created.
      throws:
        SAXException for SAX errors.
      Parameters:
        `validating` - `true` if the parser should validate documents as they are parsed; false otherwise.
        `namespaceAware` - `true` if the parser should provide support for XML namespaces; `false` otherwise.

    - #### public XmlSlurper(boolean validating, boolean namespaceAware, boolean allowDocTypeDeclaration)

      Creates a `XmlSlurper`.

      throws:
        ParserConfigurationException if no parser which satisfies the requested configuration can be created.
      throws:
        SAXException for SAX errors.
      Parameters:
        `validating` - `true` if the parser should validate documents as they are parsed; false otherwise.
        `namespaceAware` - `true` if the parser should provide support for XML namespaces; `false` otherwise.
        `allowDocTypeDeclaration` - `true` if the parser should provide support for DOCTYPE declarations; `false` otherwise.

    - #### public XmlSlurper(XMLReader reader)

      Creates a slurper backed by the supplied SAX reader.

      Parameters:
        `reader` - the XML reader whose features, properties, and handlers will be used

    - #### public XmlSlurper(SAXParser parser)

      Creates a slurper backed by the supplied SAX parser.

      throws:
        SAXException if the parser cannot provide an XML reader
      Parameters:
        `parser` - the SAX parser providing the XMLReader used for parsing

  - ### Method Detail

    - #### public void characters(char[] ch, int start, int length)

      Buffers character data until the surrounding element boundary is reached.

      throws:
        SAXException if the SAX pipeline reports an error
      Parameters:
        `ch` - the character buffer supplied by SAX
        `start` - the start offset in the buffer
        `length` - the number of characters to read

    - #### public void endDocument()

      Receives the end-of-document callback. The built tree remains available through the one-shot getDocument() result.

      throws:
        SAXException if the SAX pipeline reports an error

    - #### public void endElement(String namespaceURI, String localName, String qName)

      Flushes buffered text and restores the parent node when an end tag is reached.

      throws:
        SAXException if text handling fails
      Parameters:
        `namespaceURI` - the namespace URI, or an empty string if namespaces are unavailable
        `localName` - the local element name
        `qName` - the qualified element name as reported by SAX

    - #### public DTDHandler getDTDHandler()

      Returns the SAX DTD handler configured on the underlying reader.

      Returns:
        the configured DTD handler, or `null` if none has been set

    - #### public GPathResult getDocument()

      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

    - #### public EntityResolver getEntityResolver()

      Returns the SAX entity resolver configured on the underlying reader.

      Returns:
        the configured entity resolver, or `null` if none has been set

    - #### public ErrorHandler getErrorHandler()

      Returns the SAX error handler configured on the underlying reader.

      Returns:
        the configured error handler, or `null` if none has been set

    - #### public boolean getFeature(String uri)

      Looks up a SAX feature on the underlying reader.

      throws:
        SAXNotRecognizedException if the feature name is not recognized
      throws:
        SAXNotSupportedException if the feature is recognized but not supported
      Parameters:
        `uri` - the fully qualified SAX feature URI
      Returns:
        `true` if the feature is enabled

    - #### public Object getProperty(String uri)

      Looks up a SAX property on the underlying reader.

      throws:
        SAXNotRecognizedException if the property name is not recognized
      throws:
        SAXNotSupportedException if the property is recognized but not supported
      Parameters:
        `uri` - the fully qualified SAX property URI
      Returns:
        the current value of the property

    - #### public void ignorableWhitespace(char[] buffer, int start, int len)

      Receives ignorable whitespace and optionally preserves it as text content.

      throws:
        SAXException if the SAX pipeline reports an error
      Parameters:
        `buffer` - the character buffer supplied by SAX
        `start` - the start offset in the buffer
        `len` - the number of characters to read

    - #### public boolean isAllowDocTypeDeclaration()

      Determine if DOCTYPE declarations are allowed.

      Returns:
        true if DOCTYPE declarations are allowed
      Since:
        6.0.0

    - #### public boolean isKeepIgnorableWhitespace()

      Returns:
        true if ignorable whitespace is kept

    - #### public boolean isNamespaceAware()

      Determine if namespace handling is enabled.

      Returns:
        true if namespace handling is enabled
      Since:
        6.0.0

    - #### public boolean isValidating()

      Determine if the parser validates documents.

      Returns:
        true if validation is enabled
      Since:
        6.0.0

    - #### public GPathResult parse(InputSource input)

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

      throws:
        SAXException Any SAX exception, possibly wrapping another exception.
      throws:
        IOException An IO exception from the parser, possibly from a byte stream or character stream supplied by the application.
      Parameters:
        `input` - the InputSource to parse
      Returns:
        An object which supports GPath expressions

    - #### public GPathResult parse(File file)

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

      throws:
        SAXException Any SAX exception, possibly wrapping another exception.
      throws:
        IOException An IO exception from the parser, possibly from a byte stream or character stream supplied by the application.
      Parameters:
        `file` - the File to parse
      Returns:
        An object which supports GPath expressions

    - #### public GPathResult parse(InputStream input)

      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).

      throws:
        SAXException Any SAX exception, possibly wrapping another exception.
      throws:
        IOException An IO exception from the parser, possibly from a byte stream or character stream supplied by the application.
      Parameters:
        `input` - the InputStream to parse
      Returns:
        An object which supports GPath expressions

    - #### public GPathResult parse(Reader in)

      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).

      throws:
        SAXException Any SAX exception, possibly wrapping another exception.
      throws:
        IOException An IO exception from the parser, possibly from a byte stream or character stream supplied by the application.
      Parameters:
        `in` - the Reader to parse
      Returns:
        An object which supports GPath expressions

    - #### public GPathResult parse(String uri)

      Parse the content of the specified URI into a GPathResult Object

      throws:
        SAXException Any SAX exception, possibly wrapping another exception.
      throws:
        IOException An IO exception from the parser, possibly from a byte stream or character stream supplied by the application.
      Parameters:
        `uri` - a String containing the URI to parse
      Returns:
        An object which supports GPath expressions

    - #### public GPathResult parse(Path path)

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

      throws:
        SAXException Any SAX exception, possibly wrapping another exception.
      throws:
        IOException An IO exception from the parser, possibly from a byte stream or character stream supplied by the application.
      Parameters:
        `path` - the path of the File to parse
      Returns:
        An object which supports GPath expressions

    - #### public GPathResult parseText(String text)

      A helper method to parse the given text as XML

      throws:
        SAXException Any SAX exception, possibly wrapping another exception.
      throws:
        IOException An IO exception from the parser, possibly from a byte stream or character stream supplied by the application.
      Parameters:
        `text` - a String containing XML to parse
      Returns:
        An object which supports GPath expressions

    - #### public void setAllowDocTypeDeclaration(boolean allowDocTypeDeclaration)

      Enable and/or disable DOCTYPE declaration support. Must be set before the first parse call.

      throws:
        IllegalStateException if called after parsing has started
      Parameters:
        `allowDocTypeDeclaration` - the new desired value
      Since:
        6.0.0

    - #### public void setDTDHandler(DTDHandler dtdHandler)

      Sets the SAX DTD handler on the underlying reader.

      Parameters:
        `dtdHandler` - the DTD handler to receive notation and unparsed entity callbacks

    - #### public void setEntityBaseUrl(URL base)

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

      Parameters:
        `base` - The URL used to resolve relative URLs

    - #### public void setEntityResolver(EntityResolver entityResolver)

      Sets the SAX entity resolver on the underlying reader.

      Parameters:
        `entityResolver` - the resolver to use for external entities

    - #### public void setErrorHandler(ErrorHandler errorHandler)

      Sets the SAX error handler on the underlying reader.

      Parameters:
        `errorHandler` - the handler to receive parser warnings and errors

    - #### public void setFeature(String uri, boolean value)

      Enables or disables a SAX feature on the underlying reader.

      throws:
        SAXNotRecognizedException if the feature name is not recognized
      throws:
        SAXNotSupportedException if the feature is recognized but not supported
      Parameters:
        `uri` - the fully qualified SAX feature URI
        `value` - the value to apply

    - #### public void setKeepIgnorableWhitespace(boolean keepIgnorableWhitespace)

      Parameters:
        `keepIgnorableWhitespace` - If true then ignorable whitespace (i.e. whitespace before elements) is kept. The default is to discard the whitespace.

    - #### @Deprecated
      public void setKeepWhitespace(boolean keepWhitespace)

      deprecated:
        use setKeepIgnorableWhitespace
      Parameters:
        `keepWhitespace` - If true then whitespace before elements is kept. The default is to discard the whitespace.

    - #### public void setNamespaceAware(boolean namespaceAware)

      Enable and/or disable namespace handling. Must be set before the first parse call.

      throws:
        IllegalStateException if called after parsing has started
      Parameters:
        `namespaceAware` - the new desired value
      Since:
        6.0.0

    - #### public void setProperty(String uri, Object value)

      Sets a SAX property on the underlying reader.

      throws:
        SAXNotRecognizedException if the property name is not recognized
      throws:
        SAXNotSupportedException if the property is recognized but not supported
      Parameters:
        `uri` - the fully qualified SAX property URI
        `value` - the value to apply

    - #### public void setValidating(boolean validating)

      Enable and/or disable validation. Must be set before the first parse call.

      throws:
        IllegalStateException if called after parsing has started
      Parameters:
        `validating` - the new desired value
      Since:
        6.0.0

    - #### public void startDocument()

      Resets the current slurped document before SAX events for a new parse begin.

      throws:
        SAXException if the SAX pipeline reports an error

    - #### public void startElement(String namespaceURI, String localName, String qName, Attributes atts)

      Creates a slurper node for the current element and pushes it onto the parse stack.

      throws:
        SAXException if node creation fails
      Parameters:
        `namespaceURI` - the namespace URI, or an empty string if namespaces are unavailable
        `localName` - the local element name
        `qName` - the qualified element name as reported by SAX
        `atts` - the element attributes

    - #### public void startPrefixMapping(String tag, String uri)

      Records namespace prefix hints for later GPathResult navigation.

      throws:
        SAXException if the SAX pipeline reports an error
      Parameters:
        `tag` - the declared prefix
        `uri` - the namespace URI bound to the prefix