Example usage for javax.xml.xpath XPathFactory newInstance

List of usage examples for javax.xml.xpath XPathFactory newInstance

Introduction

In this page you can find the example usage for javax.xml.xpath XPathFactory newInstance.

Prototype

public static XPathFactory newInstance() 

Source Link

Document

Get a new XPathFactory instance using the default object model, #DEFAULT_OBJECT_MODEL_URI , the W3C DOM.

This method is functionally equivalent to:

 newInstance(DEFAULT_OBJECT_MODEL_URI) 

Since the implementation for the W3C DOM is always available, this method will never fail.

Usage

From source file:Main.java

/**
 * /*from  www  .  ja  v  a  2 s  .c o  m*/
 * <B>Purpose:</B> Evaluates an XPath and returns the Node list associated
 * witht the XPath
 * 
 * @param element
 * @param xpathstring
 * @return
 * @throws XPathExpressionException
 */
public static NodeList evaluateXPath(Element element, String xpathstring) throws XPathExpressionException {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    XPathExpression expr = xpath.compile(xpathstring);
    NodeList result = (NodeList) expr.evaluate(element, XPathConstants.NODESET);

    return result;
}

From source file:Main.java

/**
 * Returns the xml value.//from   ww  w.j a  v  a2  s  . c o  m
 * 
 * @param sIn
 * @param sxpath
 * @return
 * @throws ParserConfigurationException
 * @throws IOException
 * @throws SAXException
 * @throws XPathExpressionException
 */
public static String XPathValueFromString(String sIn, String sxpath)
        throws ParserConfigurationException, IOException, SAXException, XPathExpressionException {
    // DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    Document doc = loadXMLFromString(sIn);
    XPath xPath = XPathFactory.newInstance().newXPath();
    // XPath Query for showing all nodes value
    XPathExpression expr = xPath.compile(sxpath);

    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;
    String sReturn = "";
    for (int i = 0; i < nodes.getLength(); i++) {
        sReturn = nodes.item(i).getNodeValue();
    }
    return sReturn;
}

From source file:Main.java

public static void writeTo(Document document, File output) {
    try {//from w w w  .  j  a  v a 2 s .  com
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(document);

        FileOutputStream outputstream = new FileOutputStream(output);
        StreamResult result = new StreamResult(outputstream);

        // Manually add xml declaration, to force a newline after it.
        String xmlDeclaration = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
        outputstream.write(xmlDeclaration.getBytes());

        // Remove whitespaces outside tags.
        // Essential to make sure the nodes are properly indented.
        XPath xPath = XPathFactory.newInstance().newXPath();
        NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']", document,
                XPathConstants.NODESET);
        for (int i = 0; i < nodeList.getLength(); ++i) {
            Node node = nodeList.item(i);
            node.getParentNode().removeChild(node);
        }

        // Pretty-print options.
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        transformer.transform(source, result);

        outputstream.close();
    } catch (TransformerException | IOException | XPathExpressionException e) {
        System.out.println("Failed to write document file" + output.getPath() + ": " + e.toString());
    }
}

From source file:Main.java

/**
 * Returns a new instance of XPath./*  w ww . j  a  v  a 2 s  .c o  m*/
 *
 * @return XPath object
 */
private static XPath createXpath() {
    return XPathFactory.newInstance().newXPath();
}

From source file:Main.java

/**
 * Uses the passed XPath expression to locate a set of nodes in the passed element.
 * @param targetNode The node to search.
 * @param expression The XPath expression.
 * @return A list of located nodes./*from w w  w  . j  a v  a2s.co  m*/
 */
public static List<Node> xGetNodes(Node targetNode, String expression) {
    List<Node> nodes = new ArrayList<Node>();
    XPath xpath = null;
    try {
        xpath = XPathFactory.newInstance().newXPath();
        XPathExpression xpathExpression = xpath.compile(expression);
        NodeList nodeList = (NodeList) xpathExpression.evaluate(targetNode, NODESET);
        if (nodeList != null) {
            for (int i = 0; i < nodeList.getLength(); i++) {
                nodes.add(nodeList.item(i));
            }
        }
        return nodes;
    } catch (Exception e) {
        throw new RuntimeException("XPath:Failed to locate the nodes:" + expression, e);
    }
}

From source file:ch.entwine.weblounge.bridge.oaipmh.harvester.OaiPmhResponse.java

/**
 * Create an XPath object suitable for processing OAI-PMH response documents.
 *//* ww w .  j a v a 2 s  .c  om*/
public static XPath createXPath() {
    XPath xPath = XPathFactory.newInstance().newXPath();
    xPath.setNamespaceContext(OaiPmhNamespaceContext.getContext());
    return xPath;
}

From source file:Main.java

private static XPathExpression evaluateThePath(String xPath) throws XPathExpressionException {
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    return xpath.compile(xPath + "/text()");//small hack to get to the actual value as this is what we actually need and is mostly used
}

From source file:Main.java

/**
 * Create a map based on a xml file and a xpath expression and an attribute.
 * Treat attribute's value as map's key, treat xpath expression represented node's text content as map's value.
 * //w ww.j a va2 s . c o  m
 * @param xmlFile handled xml file
 * @param xpathExp xpath express, such as "//var"
 * @param arrtibute attribute, such as "name"
 * @return created Map object
 * @throws Exception
 */
public static Map<String, String> readXmlToMap(String xmlFile, String xpathExp, String arrtibute)
        throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setIgnoringElementContentWhitespace(true);

    DocumentBuilder db = factory.newDocumentBuilder();
    Document xmlDoc = null;
    try {
        xmlDoc = db.parse(new File(xmlFile));
    } catch (SAXException e) {
        if ("Premature end of file.".equals(e.getMessage()))
            System.out.println("Maybe your local data file has no content.");
        //e.printStackTrace();
        return new HashMap<String, String>();
    }
    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath xpath = xpathFactory.newXPath();
    NodeList varList = (NodeList) xpath.evaluate(xpathExp, xmlDoc, XPathConstants.NODESET);
    Map<String, String> dataMap = new HashMap<String, String>();
    for (int i = 0; i < varList.getLength(); i++)
        dataMap.put(varList.item(i).getAttributes().getNamedItem(arrtibute).getNodeValue(),
                varList.item(i).getTextContent());

    return dataMap;
}

From source file:Main.java

public static String getXpathValue(String xpathStr, Document doc) throws Exception {
    String value = null;//from   w ww  .j a va2  s  .c  o m
    try {
        XPath xpath = XPathFactory.newInstance().newXPath();
        Element e = (Element) xpath.evaluate(xpathStr, doc, XPathConstants.NODE);
        value = e.getTextContent();
    } catch (Exception e) {
        throw e;
    }
    return value;
}

From source file:Main.java

/**
 * Applies the specified XPath expression to the given node and returns the
 * first result./*from  ww w .j  ava2 s  .c  om*/
 * 
 * @param node the root element; the given XPath expression is applied to
 *        this node
 * @param path the XPath expression
 * @return the first node corresponding to the specified XPath expression
 * @throws XPathExpressionException
 */
public static Node evalFirst(Node node, String path) throws XPathExpressionException {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    XPathExpression expr = xpath.compile(path);
    final Node result = (Node) expr.evaluate(node, XPathConstants.NODE);
    return result;
}