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

/**
 * Execute an xpath query on a specific node.
 *
 * The type parameter specifies the expected type of the result of the
 * query. Typical types are:/*  www. java 2 s. c  o m*/
 *
 *  XPathContants.NUMBER: A java Double that corresponds to a numeric
 *  literal in the XML document
 *  XPathConstants.STRING: A java String that corresponds to a text literal
 *  in the XML document
 *  XPathConstants.NODESET: A NodeList that contains a list of nodes
 *  in the XML document
 *  XPathConstants.NODE: A particular Node inside the XML document
 *
 * @param doc The node on which the xpath expression is to be executed
 * @param xpath_expr The XPath expression to be executed
 * @param type One of the XPathConstants that specified the expected output.
 * @return The result of the XPath query on the node, of the corresponding
 *         type
 */
@SuppressWarnings("unchecked")
public static <T> T xpath(Node doc, String xpath_expr, QName type) {
    XPathFactory xpathfactory = XPathFactory.newInstance();
    XPath xpath = xpathfactory.newXPath();
    XPathExpression expr;
    try {
        expr = xpath.compile(xpath_expr);
        return (T) expr.evaluate(doc, type);
    } catch (XPathExpressionException e) {
        throw new RuntimeException(e);
    }
}

From source file:Main.java

public static boolean updateDBConfig(String userName, String password, String name, String driver, String url,
        String dbConfigPath) throws XPathExpressionException, ParserConfigurationException, SAXException,
        IOException, TransformerException {
    Document document = loadXML(dbConfigPath);

    XPath path = XPathFactory.newInstance().newXPath();
    XPathExpression express = path.compile(
            "//Configure/New[@class='org.eclipse.jetty.plus.jndi.Resource']/Arg/New[@class='bitronix.tm.resource.jdbc.PoolingDataSource']/Set[@name='className']");

    NodeList nodes = (NodeList) express.evaluate(document, XPathConstants.NODESET);
    Node node = nodes.item(0);//from ww w  .  ja  v  a2  s .  co  m
    node.setTextContent(driver);
    path.reset();

    express = path.compile(
            "//Configure/New[@class='org.eclipse.jetty.plus.jndi.Resource']/Arg/New[@class='bitronix.tm.resource.jdbc.PoolingDataSource']/Get['@name=driverProperties']/Put");
    nodes = (NodeList) express.evaluate(document, XPathConstants.NODESET);

    for (int i = 0; i < nodes.getLength(); i++) {
        node = nodes.item(i);
        if ("user".equals(node.getAttributes().item(0).getTextContent())) {
            node.setTextContent(userName);
        } else if ("password".equals(node.getAttributes().item(0).getTextContent())) {
            node.setTextContent(password);
        } else if ("URL".equals(node.getAttributes().item(0).getTextContent())) {
            //            String url = node.getTextContent();
            //            System.out.println("basic url ---> " + url + "; name -->" + name);
            //            url = replaceDBName("examples", name, url);
            //            System.out.println("dist url ---> " + url);
            node.setTextContent(url);
        }
    }
    path.reset();

    return updateXML(document, dbConfigPath);
}

From source file:Main.java

public static boolean updatePomDBConfig(String userName, String password, String name, String host, String port,
        String version, String pomPath) throws ParserConfigurationException, SAXException, IOException,
        XPathExpressionException, TransformerException {
    Document document = loadXML(pomPath);
    XPath path = XPathFactory.newInstance().newXPath();
    XPathExpression express = path.compile("//project/properties/mysql.server.version");

    NodeList nodes = (NodeList) express.evaluate(document, XPathConstants.NODESET);
    Node node = nodes.item(0);/*  w  w w . j a va2  s. com*/
    node.setTextContent(version);
    path.reset();

    express = path.compile("//project/properties/mysql.server.host");
    nodes = (NodeList) express.evaluate(document, XPathConstants.NODESET);
    node = nodes.item(0);
    node.setTextContent(host);
    path.reset();

    express = path.compile("//project/properties/mysql.server.port");
    nodes = (NodeList) express.evaluate(document, XPathConstants.NODESET);
    node = nodes.item(0);
    node.setTextContent(port);
    path.reset();

    express = path.compile("//project/properties/mysql.server.database");
    nodes = (NodeList) express.evaluate(document, XPathConstants.NODESET);
    node = nodes.item(0);
    node.setTextContent(name);
    path.reset();

    express = path.compile("//project/properties/mysql.server.user");
    nodes = (NodeList) express.evaluate(document, XPathConstants.NODESET);
    node = nodes.item(0);
    node.setTextContent(userName);
    path.reset();

    express = path.compile("//project/properties/mysql.server.password");
    nodes = (NodeList) express.evaluate(document, XPathConstants.NODESET);
    node = nodes.item(0);
    node.setTextContent(password);
    path.reset();

    return updateXML(document, pomPath);
}

From source file:Main.java

private static Document getDoc(String filePath) throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);// w w w  . ja v a 2 s . c  o m
    DocumentBuilder builder = null;
    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath xpath = xpathFactory.newXPath();
    builder = factory.newDocumentBuilder();
    Document doc = builder.parse(filePath);

    return doc;
}

From source file:Main.java

public static String setValueXPath(String srcXmlString, String xPath, String newVal) {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(false); // never forget this!
    int i, j;//from   w w  w  .j  a  v a2 s .co  m
    Document doc = null;
    DocumentBuilder builder = null;
    try {
        builder = domFactory.newDocumentBuilder();
        doc = builder.parse(new ByteArrayInputStream(srcXmlString.getBytes()));
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression expr = xpath.compile(xPath);

        Object result = expr.evaluate(doc, XPathConstants.NODESET);

        NodeList xPathNodes = (NodeList) result;
        logger.debug("xpath result count: " + xPathNodes.getLength());
        logger.debug(xPathNodes.item(0).getNodeName() + " = " + xPathNodes.item(0).getTextContent());

        // get list of all nodes in doc
        NodeList nodes = doc.getElementsByTagName("*");
        // iterate through all the nodes
        for (i = 0; i < xPathNodes.getLength(); i++) {
            // for each node in xpath result - traverse through all nodes in
            // doc to find match
            for (j = 0; j < nodes.getLength(); j++) {
                if (nodes.item(j).isSameNode(xPathNodes.item(i))) {
                    logger.debug("Old value " + i + ": " + xPathNodes.item(i).getNodeName() + " = "
                            + xPathNodes.item(i).getTextContent());
                    nodes.item(j).setTextContent(newVal);
                    logger.debug("New value " + i + ": " + xPathNodes.item(i).getNodeName() + " = "
                            + xPathNodes.item(i).getTextContent());
                    break;
                }
            }
        }
    } catch (Exception ex) {
        logger.error(ex.getMessage());
        // ex.printStackTrace();
    }
    return getW3CXmlFromDoc(doc);
}

From source file:Main.java

/**
 * Locates the attribute defined by the XPath expression in the XML file and replaces it with the passed value.
 * @param fileName The XML file to update.
 * @param xPathExpression An XPath expression that locates the attribute to update.
 * @param attributeName The name of the attribute to update.
 * @param value The value to update the attribute to.
 *//*from   ww  w  . ja v a 2 s. c  o m*/
public static void updateAttributeInXMLFile(String fileName, String xPathExpression, String attributeName,
        String value) {
    try {
        Document document = parseXML(new File(fileName));
        XPath xpath = XPathFactory.newInstance().newXPath();
        XPathExpression xpathExpression = xpath.compile(xPathExpression);
        Element element = (Element) xpathExpression.evaluate(document, NODE);

        element.getAttributeNode(attributeName).setValue(value);
        writeElement(document.getDocumentElement(), fileName);

    } catch (Exception e) {
        throw new RuntimeException("Failed to extract element from:" + fileName, e);
    }
}

From source file:Main.java

/**
 * Get the searchHandler Node from the solrconfig.xml file
 *
 * @param solrconfig// w  w  w .j av a2s.  c om
 *            the solrconfig.xml File
 *
 * @return searchHandler XML Node or null if not found
 *
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 * @throws XPathExpressionException
 */
public static Node getSearchHandlerNode(final File solrconfig)
        throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
    final DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    final DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    final Document docSchem = dBuilder.parse(solrconfig);
    final XPathFactory xPathfactory = XPathFactory.newInstance();
    final XPath xpath = xPathfactory.newXPath();
    final XPathExpression expr = xpath
            .compile("//requestHandler[@class=\"solr.SearchHandler\" and @name=\"/select\"]");
    final Node requestHandler = (Node) expr.evaluate(docSchem, XPathConstants.NODE);
    return requestHandler;
}

From source file:Main.java

public static Node selectSingleNode(Node node, String express) {
    Node result = null;/*from  w w w.j a  v  a  2  s  . c  o m*/
    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath xpath = xpathFactory.newXPath();
    try {
        result = (Node) xpath.evaluate(express, node, XPathConstants.NODE);
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }

    return result;
}

From source file:Main.java

public static Object execXpathGetNode(String srcXmlString, String xPath) {
    Object result = null;/*from w w  w  . j a  va 2 s . c  om*/
    try {
        Document doc = stringToDoc(srcXmlString);
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression expr = xpath.compile(xPath);
        result = expr.evaluate(doc, XPathConstants.NODE);
    } catch (Exception ex) {
        logger.error(ex);
    }
    return result;
}

From source file:Main.java

/**
 * Evaluate an XPath against a Document, returning a String.
 * /*from   w  w  w  .  j av a  2  s .co m*/
 * @param doc Document
 * @param xp XPath to evaluate against Document
 * @return String found at path or null
 */
public static String xpathOrNull(Document doc, String xp) {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    try {
        XPathExpression expr = xpath.compile(xp);
        return expr.evaluate(doc);
    } catch (XPathExpressionException e) {
        return null;
    }
}