Created
February 12, 2014 15:38
-
-
Save octavian-nita/8957794 to your computer and use it in GitHub Desktop.
XML-handling utilities
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 static javax.xml.xpath.XPathConstants.NODESET; | |
import java.io.BufferedReader; | |
import java.io.File; | |
import java.io.FileReader; | |
import java.io.IOException; | |
import java.io.Reader; | |
import java.io.StringReader; | |
import java.util.ArrayList; | |
import java.util.List; | |
import javax.xml.parsers.DocumentBuilder; | |
import javax.xml.parsers.DocumentBuilderFactory; | |
import javax.xml.parsers.ParserConfigurationException; | |
import javax.xml.xpath.XPath; | |
import javax.xml.xpath.XPathFactory; | |
import org.apache.log4j.Logger; | |
import org.w3c.dom.Element; | |
import org.w3c.dom.Node; | |
import org.w3c.dom.NodeList; | |
import org.xml.sax.InputSource; | |
/** | |
* Convenience class containing various XML-handling utilities. | |
* | |
* @author nitanoc | |
* @version 1.0, Feb 7, 2014 | |
*/ | |
public class XmlUtils { | |
/** | |
* Convenience instance: normally only one instance of this class is needed. | |
* | |
* <pre> | |
* import static ...XmlUtils.XML; | |
* ... | |
* Element root1 = XML.parse(content); | |
* ... | |
* Element root2 = XML.parse(new File("input.xml")); | |
* </pre> | |
*/ | |
public static final XmlUtils XML = new XmlUtils(); | |
protected static final Logger log = Logger.getLogger(XmlUtils.class); | |
protected static final void notNull(Object object, String message) { | |
if (object == null) { | |
throw new NullPointerException(message); | |
} | |
} | |
protected DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); | |
protected DocumentBuilder documentBuilder; | |
protected XPathFactory xPathFactory = XPathFactory.newInstance(); | |
protected XPath xPath = xPathFactory.newXPath(); | |
public XmlUtils() { | |
this(true); | |
} | |
public XmlUtils(boolean namespaceAware) { | |
documentBuilderFactory.setNamespaceAware(namespaceAware); | |
try { | |
documentBuilder = documentBuilderFactory.newDocumentBuilder(); | |
} catch (ParserConfigurationException e) { | |
throw new IllegalStateException("cannot create a document builder", e); | |
} | |
} | |
public Element parse(File file) { | |
Reader reader = null; | |
try { | |
return documentBuilder.parse(new InputSource(reader = new BufferedReader(new FileReader(file)))) | |
.getDocumentElement(); | |
} catch (Throwable throwable) { | |
log.error("cannot parse XML from specified source " + file.getAbsolutePath(), throwable); | |
return null; | |
} finally { | |
if (reader != null) { | |
try { | |
reader.close(); | |
} catch (IOException ioe) { | |
log.warn("cannot close specified source " + file.getAbsolutePath() + "; ignoring...", ioe); | |
} | |
} | |
} | |
} | |
public Element parse(String content) { | |
notNull(content, "cannot parse a null XML content"); | |
try { | |
return documentBuilder.parse(new InputSource(new StringReader(content))).getDocumentElement(); | |
} catch (Throwable e) { | |
String nl = System.getProperty("line.separator", "\n"); | |
log.error("cannot parse specified XML content:" + nl + content + nl, e); | |
return null; | |
} | |
} | |
public Node[] children(Node node) { | |
notNull(node, "cannot get the children of a null element"); | |
List<Node> children = new ArrayList<Node>(); | |
NodeList childNodes = node.getChildNodes(); | |
int childCount = childNodes.getLength(); | |
for (int i = 0; i < childCount; i++) { | |
children.add(childNodes.item(i)); | |
} | |
return children.toArray(new Node[children.size()]); | |
} | |
public Node[] nodes(Node root) { | |
return nodes(root, null); | |
} | |
public Node[] nodes(Node node, String expression) { | |
notNull(node, "cannot get the (sub)nodes of a null node"); | |
if (expression == null) { | |
expression = "*"; | |
} | |
try { | |
NodeList nodeList = (NodeList) xPath.evaluate(expression, node, NODESET); | |
int nodeCount = nodeList.getLength(); | |
Node[] nodes = new Node[nodeCount]; | |
for (int i = 0; i < nodeCount; i++) { | |
nodes[i] = nodeList.item(i); | |
} | |
return nodes; | |
} catch (Throwable throwable) { | |
log.error("cannot get the (sub)nodes of the specified node using expression " + expression, throwable); | |
return new Node[]{}; // avoids NPE in case someone iterates without checking first... | |
} | |
} | |
public String val(Node node, String expression) { | |
try { | |
return xPath.evaluate(expression == null ? "" : expression, node); | |
} catch (Throwable throwable) { | |
log.error("cannot get the String value of the specified node using expression " + expression, throwable); | |
return null; | |
} | |
} | |
public String val(Node node) { | |
return val(node, true); | |
} | |
public String val(Node node, boolean trimText) { | |
notNull(node, "cannot get the value of a null node"); | |
String val = node.getNodeValue(); | |
return val == null ? null : trimText ? val.trim() : val; | |
} | |
public String text(Node node) { | |
return text(node, true); | |
} | |
public String text(Node node, boolean trim) { | |
notNull(node, "cannot get the text of a null node"); | |
return trim ? node.getTextContent().trim() : node.getTextContent(); | |
} | |
public String attr(Node node, String attribute) { | |
return node != null && node instanceof Element ? attr((Element) node, attribute, true) : null; | |
} | |
public String attr(Node node, String attribute, boolean trimValue) { | |
return node != null && node instanceof Element ? attr((Element) node, attribute, trimValue) : null; | |
} | |
public String attr(Element element, String attribute) { | |
return attr(element, attribute, true); // retrieved attribute values are trimmed by default... | |
} | |
public String attr(Element element, String attribute, boolean trimValue) { | |
notNull(element, "cannot get an attribute of a null element"); | |
notNull(attribute, "cannot get an attribute with a null name"); | |
String attributeValue = element.getAttribute(attribute); | |
return attributeValue != null ? trimValue ? attributeValue.trim() : attributeValue : attributeValue; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment