XmlSlurper in Groovy

This class belongs to the  package groovy.util.XmlSlurper. The XmlSlurper is very useful in groovy to handle XML related operations

 

The constructor XmlSlurper() can be used to create a very loose (non-validating and namespace-aware) instance.

XmlSlurper parsers
The parse method has many flavors. The parse method returns a GPathResult object.

parse(File file) : XML file can be parsed directly
parse(InputSource input) : Parse the content of input source
parse(InputStream input) : Any binary input stream which refers to XML
parse(Reader in): Using a Reader instance
parse(String uri): URI eg: http://www.helicaltech.com/test.xml
parseText(String text): A helper method to parse the given text as XML

GPathResult

This is the key object which helps in navigating the xml object parsed by XmlSlurper

Some important method of the GPathResult
breadthFirst(): Provides an Iterator over all the nodes using a breadth-first traversal.
childNodes(): Returns an iterator over the child nodes
children(): Returns the children of this GPathResult as a GPathResult object.
declareNamespace(Map newNamespaceMapping): Adds the specified map of prefix to namespace mappings to this GPathResult.
depthFirst() :Provides an Iterator over all using depth-first traversal.
find(Closure closure) :Returns the first child matching the condition(s) specified in the passed closure.
name(): Returns the name of element
parent(): Returns as parent nodes
size() : Returns the size of this GPathResult.
text(): Returns the text of this GPathResult as a String.

 

nodetree

 

Leave a Reply