Skip to content

Instantly share code, notes, and snippets.

@aib
Last active August 29, 2015 14:15
Show Gist options
  • Save aib/47e41b50802bda25c9c8 to your computer and use it in GitHub Desktop.
Save aib/47e41b50802bda25c9c8 to your computer and use it in GitHub Desktop.
Java easy XML
//My notes on doing XML stuff in Java, as simply as possible
//not production quality, obviously
//XML parsing
DocumentBuilder db = null;
try {
db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
} catch (ParserConfigurationException e) {
}
Document dom = null;
try {
dom = db.parse(new ByteArrayInputStream(xmlString.getBytes(StandardCharsets.UTF_8)));
dom.setXmlStandalone(true); //else we get the standalone="no" attribute in the XML declaration
} catch (SAXException e) {
} catch (IOException e) {
}
//XML printing
try {
Transformer t = TransformerFactory.newInstance().newTransformer();
StringWriter sw = new StringWriter();
t.transform(new DOMSource(node), new StreamResult(sw));
return sw.getBuffer().toString();
} catch (TransformerConfigurationException e) {
} catch (TransformerFactoryConfigurationError e) {
} catch (TransformerException e) {
}
//Node querying and manipulation with XPath
try {
XPath xp = XPathFactory.newInstance().newXPath();
//directly from String
String s = xp.compile("/root/auth/login/text()").evaluate(new InputSource(new ByteArrayInputStream(xmlString.getBytes(StandardCharsets.UTF_8))));
//from a parsed DOM (Document class)
Node n = (Node) xp.compile("/root/auth/login/text()").evaluate(dom, XPathConstants.NODE);
n.setNodeValue("username");
} catch (XPathExpressionException e) {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment