Package: groovy.xml

## [Java] Class XmlParser

- groovy.xml.XmlParser

- All Implemented Interfaces and Traits:
    ContentHandler

      public class XmlParser
      extends Object
      implements ContentHandler

  A helper class for parsing XML into a tree of Node instances for a simple way of processing XML. This parser does not preserve the XML InfoSet - if that's what you need try using W3C DOM, dom4j, JDOM, XOM etc. This parser ignores comments and processing instructions and converts the XML into a Node for each element in the XML with attributes and child Nodes and Strings. This simple model is sufficient for most simple use cases of processing XML. Parsing is eager: each parse operation consumes the SAX event stream and builds a complete Node tree before returning.

  Example usage:

       import groovy.xml.XmlParser
       def xml = '<root><one a1="uno!"/><two>Some text!</two></root>'
       def rootNode = new XmlParser().parseText(xml)
       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'] }

  `XmlParser` builds the whole document into a `groovy.util.Node` tree in memory. For very large documents, bound the input size or use a streaming / Jackson-based parser instead (e.g. `jackson-dataformat-xml`); Groovy interoperates cleanly with Jackson.

- - ### Constructor Summary

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

  - ### Methods Summary

    Methods
    Type Params | Return Type | Name and description
    --- | --- | ---
    `` | `protected void` | `addTextToNode()` Transfers buffered character data into the current node when an element boundary is reached.
    `` | `public void` | `characters(char[] buffer, int start, int length)` Buffers character data until the enclosing element boundary is reached.
    `` | `protected Node` | `createNode(Node parent, Object name, Map attributes)` Creates a new node with the given parent, name, and attributes.
    `` | `public void` | `endDocument()` Completes the current parse and clears the internal element stack.
    `` | `public void` | `endElement(String namespaceURI, String localName, String qName)` Flushes buffered text and pops the current element when its end tag is seen.
    `` | `public void` | `endPrefixMapping(String prefix)` Receives namespace prefix scope end notifications.
    `` | `public DTDHandler` | `getDTDHandler()` Returns the SAX DTD handler configured on the underlying reader.
    `` | `public Locator` | `getDocumentLocator()` Returns the document locator last provided by SAX.
    `` | `protected Object` | `getElementName(String namespaceURI, String localName, String qName)` Return a name given the namespaceURI, localName and qName.
    `` | `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.
    `` | `protected XMLReader` | `getXMLReader()` Returns the configured XML reader after registering this parser as its content handler.
    `` | `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 the current keep ignorable whitespace setting.
    `` | `public boolean` | `isNamespaceAware()` Determine if namespace handling is enabled.
    `` | `public boolean` | `isTrimWhitespace()` Returns the current trim whitespace setting.
    `` | `public boolean` | `isValidating()` Determine if the parser validates documents.
    `` | `public Node` | `parse(File file)` Parses the content of the given file as XML turning it into a tree of Nodes.
    `` | `public Node` | `parse(Path path)` Parses the content of the file at the given path as XML turning it into a tree of Nodes.
    `` | `public Node` | `parse(InputSource input)` Parse the content of the specified input source into a tree of Nodes.
    `` | `public Node` | `parse(InputStream input)` Parse the content of the specified input stream into a tree of Nodes.
    `` | `public Node` | `parse(Reader in)` Parse the content of the specified reader into a tree of Nodes.
    `` | `public Node` | `parse(String uri)` Parse the content of the specified URI into a tree of Nodes.
    `<T>` | `public T` | `parseAs(Class<T> type, Reader reader)` Parse XML from a reader into a typed object.
    `<T>` | `public T` | `parseAs(Class<T> type, InputStream stream)` Parse XML from an input stream into a typed object.
    `<T>` | `public T` | `parseAs(Class<T> type, File file)` Parse XML from a file into a typed object.
    `<T>` | `public T` | `parseAs(Class<T> type, Path path)` Parse XML from a path into a typed object.
    `` | `public Node` | `parseText(String text)` A helper method to parse the given text as XML.
    `<T>` | `public T` | `parseTextAs(Class<T> type, String text)` Parse the content of the specified XML text into a typed object.
    `` | `public void` | `processingInstruction(String target, String data)` Receives processing instruction callbacks.
    `` | `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` | `setDocumentLocator(Locator locator)` Stores the locator supplied by SAX for later diagnostics or subclass use.
    `` | `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)` Sets the keep ignorable whitespace setting value.
    `` | `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` | `setTrimWhitespace(boolean trimWhitespace)` Sets the trim whitespace setting value.
    `` | `public void` | `setValidating(boolean validating)` Enable and/or disable validation.
    `` | `public void` | `skippedEntity(String name)` Receives skipped entity notifications.
    `` | `public void` | `startDocument()` Resets the current root node before SAX events for a new document begin.
    `` | `public void` | `startElement(String namespaceURI, String localName, String qName, Attributes list)` Creates a new Node for the current element and pushes it onto the parse stack.
    `` | `public void` | `startPrefixMapping(String prefix, String namespaceURI)` Receives namespace prefix mapping notifications.

  - ### Inherited Methods Summary

    Inherited Methods
    Methods inherited from class | Name
    --- | ---
    `class Object` | `equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

- - ### Constructor Detail

    - #### public XmlParser()

      Creates a non-validating and namespace-aware `XmlParser` 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 parser = new XmlParser(namespaceAware: false, trimWhitespace: true)

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

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

      Creates a `XmlParser` 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 XmlParser(boolean validating, boolean namespaceAware, boolean allowDocTypeDeclaration)

      Creates a `XmlParser`.

      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 XmlParser(XMLReader reader)

      Creates a parser backed by the supplied SAX reader.

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

    - #### public XmlParser(SAXParser parser)

      Creates a parser 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

    - #### protected void addTextToNode()

      Transfers buffered character data into the current node when an element boundary is reached. Subclasses may override to customize text normalization or whitespace preservation during parsing.

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

      Buffers character data until the enclosing element boundary is reached.

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

    - #### protected Node createNode(Node parent, Object name, Map attributes)

      Creates a new node with the given parent, name, and attributes. The default implementation returns an instance of `groovy.util.Node`.

      Parameters:
        `parent` - the parent node, or null if the node being created is the root node
        `name` - an Object representing the name of the node (typically an instance of QName)
        `attributes` - a Map of attribute names to attribute values
      Returns:
        a new Node instance representing the current node

    - #### public void endDocument()

      Completes the current parse and clears the internal element stack.

      throws:
        SAXException if the SAX pipeline reports an error

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

      Flushes buffered text and pops the current element when its end tag is seen.

      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 void endPrefixMapping(String prefix)

      Receives namespace prefix scope end notifications. The default implementation performs no action.

      throws:
        SAXException if the SAX pipeline reports an error
      Parameters:
        `prefix` - the prefix leaving scope

    - #### 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 Locator getDocumentLocator()

      Returns the document locator last provided by SAX.

      Returns:
        the current locator, or `null` if parsing has not started

    - #### protected Object getElementName(String namespaceURI, String localName, String qName)

      Return a name given the namespaceURI, localName and qName.

      Parameters:
        `namespaceURI` - the namespace URI
        `localName` - the local name
        `qName` - the qualified name
      Returns:
        the newly created representation of the name

    - #### 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

    - #### protected XMLReader getXMLReader()

      Returns the configured XML reader after registering this parser as its content handler. Subclasses may override to customize reader preparation before parsing begins.

      Returns:
        the XML reader used for subsequent parse operations

    - #### 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 the current keep ignorable whitespace setting.

      Returns:
        true if ignorable whitespace will be kept (default false)

    - #### public boolean isNamespaceAware()

      Determine if namespace handling is enabled.

      Returns:
        true if namespace handling is enabled

    - #### public boolean isTrimWhitespace()

      Returns the current trim whitespace setting.

      Returns:
        true if whitespace will be trimmed

    - #### public boolean isValidating()

      Determine if the parser validates documents.

      Returns:
        true if validation is enabled
      Since:
        6.0.0

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

      Parses the content of the given file as XML turning it into a tree of Nodes.

      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 containing the XML to be parsed
      Returns:
        the root node of the parsed tree of Nodes

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

      Parses the content of the file at the given path as XML turning it into a tree of Nodes.

      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 containing the XML to be parsed
      Returns:
        the root node of the parsed tree of Nodes

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

      Parse the content of the specified input source into a tree of Nodes.

      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 for the XML to parse
      Returns:
        the root node of the parsed tree of Nodes

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

      Parse the content of the specified input stream into a tree of Nodes.

      Note that using this method will not provide the parser with any URI for which to find DTDs etc

      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` - an InputStream containing the XML to be parsed
      Returns:
        the root node of the parsed tree of Nodes

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

      Parse the content of the specified reader into a tree of Nodes.

      Note that using this method will not provide the parser with any URI for which to find DTDs etc

      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` - a Reader to read the XML to be parsed
      Returns:
        the root node of the parsed tree of Nodes

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

      Parse the content of the specified URI into a tree of Nodes.

      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 a URI pointing to the XML to be parsed
      Returns:
        the root node of the parsed tree of Nodes

    - #### <T> public T parseAs(Class<T> type, Reader reader)

      Parse XML from a reader into a typed object. Requires jackson-databind on the classpath for type conversion.

      throws:
        XmlRuntimeException if parsing or conversion fails, or jackson-databind is absent
      Parameters:
        `type` - the target type
        `reader` - the reader of XML
      Type Parameters:
        `T` - the target type
      Returns:
        a typed object
      Since:
        6.0.0

    - #### <T> public T parseAs(Class<T> type, InputStream stream)

      Parse XML from an input stream into a typed object. Requires jackson-databind on the classpath for type conversion.

      throws:
        XmlRuntimeException if parsing or conversion fails, or jackson-databind is absent
      Parameters:
        `type` - the target type
        `stream` - the input stream of XML
      Type Parameters:
        `T` - the target type
      Returns:
        a typed object
      Since:
        6.0.0

    - #### <T> public T parseAs(Class<T> type, File file)

      Parse XML from a file into a typed object. Requires jackson-databind on the classpath for type conversion.

      throws:
        IOException if the file cannot be read
      throws:
        XmlRuntimeException if parsing or conversion fails, or jackson-databind is absent
      Parameters:
        `type` - the target type
        `file` - the XML file
      Type Parameters:
        `T` - the target type
      Returns:
        a typed object
      Since:
        6.0.0

    - #### <T> public T parseAs(Class<T> type, Path path)

      Parse XML from a path into a typed object. Requires jackson-databind on the classpath for type conversion.

      throws:
        IOException if the file cannot be read
      throws:
        XmlRuntimeException if parsing or conversion fails, or jackson-databind is absent
      Parameters:
        `type` - the target type
        `path` - the path to the XML file
      Type Parameters:
        `T` - the target type
      Returns:
        a typed object
      Since:
        6.0.0

    - #### public Node 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` - the XML text to parse
      Returns:
        the root node of the parsed tree of Nodes

    - #### <T> public T parseTextAs(Class<T> type, String text)

      Parse the content of the specified XML text into a typed object. Requires jackson-databind on the classpath for type conversion. Supports `@JsonProperty` and `@JsonFormat` annotations.

      throws:
        XmlRuntimeException if parsing or conversion fails, or jackson-databind is absent
      Parameters:
        `type` - the target type
        `text` - the XML text to parse
      Type Parameters:
        `T` - the target type
      Returns:
        a typed object
      Since:
        6.0.0

    - #### public void processingInstruction(String target, String data)

      Receives processing instruction callbacks. The default implementation ignores processing instructions.

      throws:
        SAXException if the SAX pipeline reports an error
      Parameters:
        `target` - the processing instruction target
        `data` - the processing instruction data

    - #### 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 setDocumentLocator(Locator locator)

      Stores the locator supplied by SAX for later diagnostics or subclass use.

      Parameters:
        `locator` - the document locator for the current parse

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

      Sets the keep ignorable whitespace setting value.

      Parameters:
        `keepIgnorableWhitespace` - the desired new value

    - #### 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

    - #### 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 setTrimWhitespace(boolean trimWhitespace)

      Sets the trim whitespace setting value.

      Parameters:
        `trimWhitespace` - the desired setting value

    - #### 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 skippedEntity(String name)

      Receives skipped entity notifications. The default implementation performs no action.

      throws:
        SAXException if the SAX pipeline reports an error
      Parameters:
        `name` - the skipped entity name

    - #### public void startDocument()

      Resets the current root node before SAX events for a new document begin.

      throws:
        SAXException if the SAX pipeline reports an error

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

      Creates a new 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
        `list` - the element attributes

    - #### public void startPrefixMapping(String prefix, String namespaceURI)

      Receives namespace prefix mapping notifications. The default implementation does not retain separate prefix state.

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