Skip to content

Instantly share code, notes, and snippets.

@miceno
Created January 2, 2011 11:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miceno/762463 to your computer and use it in GitHub Desktop.
Save miceno/762463 to your computer and use it in GitHub Desktop.
Reading XML with Java DocumentBuilder parsing with Java XPath
// Groovy: Reading XML with Java DocumentBuilder parsing with Java XPath
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.*
import org.w3c.dom.Document;
File f= new File( 'data.xml')
// Reading a Document Builder with Java style
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(f);
println "document =" + doc.getDocumentElement().textContent
// Parsing
String XPATH_EXPRESSION="//entry"
// Parsing with Java Xpath
def xp = XPathFactory.newInstance().newXPath()
def expr = xp.compile(XPATH_EXPRESSION)
def nodes = expr.evaluate(doc, XPathConstants.NODESET)
nodes.each{ println "Element ${it.name}: ${it.textContent}" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment