Skip to content

Instantly share code, notes, and snippets.

@brianjriddle
Created June 1, 2012 18:57
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 brianjriddle/2854382 to your computer and use it in GitHub Desktop.
Save brianjriddle/2854382 to your computer and use it in GitHub Desktop.
Parsing xml so my eyes don't bleed
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import se.tv4.teknik.vman.api.XmlDataReader;
import javax.xml.parsers.*;
import javax.xml.xpath.XPathConstants;
import java.io.*;
import java.util.*;
public class Asset {
private String id;
private Document document;
public Asset() {
}
public Asset(InputStream inputStream) throws SAXException, IOException {
try {
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
builder = domFactory.newDocumentBuilder();
document = builder.parse(inputStream);
XmlDataReader xmlDataReader = new XmlDataReader(document);
setId(xmlDataReader.read("/asset/@id", XPathConstants.STRING).toString());
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
import org.w3c.dom.Document;
import javax.xml.namespace.QName;
import javax.xml.xpath.*;
public class XmlDataReader {
private final Document document;
public XmlDataReader(Document document) {
this.document = document;
}
public Object read(String expression, QName returnType) {
try {
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression xPathExpression = xpath.compile(expression);
return xPathExpression.evaluate(document, returnType);
} catch (XPathExpressionException ex) {
ex.printStackTrace();
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment