Created
June 1, 2012 18:57
-
-
Save brianjriddle/2854382 to your computer and use it in GitHub Desktop.
Parsing xml so my eyes don't bleed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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