Example usage for javax.xml.xpath XPathFactory newXPath

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

Introduction

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

Prototype

public abstract XPath newXPath();

Source Link

Document

Return a new XPath using the underlying object model determined when the XPathFactory was instantiated.

Usage

From source file:com.thinkbiganalytics.feedmgr.nifi.NifiTemplateParser.java

public static String updateTemplateName(String nifiTemplate, String newName) throws Exception {

    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath xpath = xpathFactory.newXPath();
    Document doc = stringToDocument(nifiTemplate);

    InputSource source = new InputSource(new StringReader(nifiTemplate));

    Element element = (Element) xpath.compile("//template/name").evaluate(doc, XPathConstants.NODE);

    element.setTextContent(newName);//from w w  w  .  j a  v  a  2 s.c  o  m
    return documentToString(doc);
}

From source file:Main.java

private static XPathExpression createXPathExpression(String xpathString) {
    /* XPath *///from  w  w w  . java2s  .c o m
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    xpath.setNamespaceContext(new NamespaceContext() {

        @Override
        public Iterator<?> getPrefixes(String namespaceURI) {
            throw new RuntimeException();
        }

        @Override
        public String getPrefix(String namespaceURI) {
            throw new RuntimeException();
        }

        @Override
        public String getNamespaceURI(String prefix) {
            if ("ds".equals(prefix)) {
                return XMLSignature.XMLNS;
            } else if ("xades".equals(prefix)) {
                return "http://uri.etsi.org/01903/v1.3.2#";
            } else if ("xades141".equals(prefix)) {
                return "http://uri.etsi.org/01903/v1.4.1#";
            } else if ("xades111".equals(prefix)) {
                return "http://uri.etsi.org/01903/v1.1.1#";
            }
            throw new RuntimeException("Prefix not recognized : " + prefix);
        }
    });
    try {
        XPathExpression expr = xpath.compile(xpathString);
        return expr;
    } catch (XPathExpressionException ex) {
        throw new RuntimeException(ex);
    }

}

From source file:Main.java

public static Node selectSingleNode(final Node sourceNode, final String xPathExpression) {
    Node result;// www. j  ava 2  s  .c  om
    XPathFactory factory = XPathFactory.newInstance(); // http://www.ibm.com/developerworks/library/x-javaxpathapi/index.html
    XPath xPathParser = factory.newXPath();

    try {
        result = (Node) xPathParser.evaluate(xPathExpression, sourceNode, XPathConstants.NODE);
    } catch (XPathExpressionException e) {
        result = null;
    }

    return result;
}

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  www .  j  a  v  a  2  s  .c om
    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:com.thoughtworks.go.util.XpathUtils.java

private static String evaluate(XPathFactory factory, InputSource inputSource, String xpath)
        throws XPathExpressionException {
    XPathExpression expression = factory.newXPath().compile(xpath);
    return expression.evaluate(inputSource).trim();
}

From source file:Main.java

public static final String[] executeXPathExpression(InputSource inputSource, String xpathExpression,
        String namespace) throws XPathExpressionException, SAXException, IOException,
        ParserConfigurationException, TransformerException {

    // optional namespace spec: xmlns:prefix:URI
    String nsPrefix = null;/*from ww w . j  a  v a  2 s.  c  o m*/
    String nsUri = null;
    if (namespace != null && namespace.startsWith("xmlns:")) {
        String[] nsDef = namespace.substring("xmlns:".length()).split("=");
        if (nsDef.length == 2) {
            nsPrefix = nsDef[0];
            nsUri = nsDef[1];
        }
    }

    // Parse XML to DOM
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    dbFactory.setNamespaceAware(true);
    Document doc = dbFactory.newDocumentBuilder().parse(inputSource);

    // Find nodes by XPATH
    XPathFactory xpFactory = XPathFactory.newInstance();
    XPath xpath = xpFactory.newXPath();

    // namespace?
    if (nsPrefix != null) {
        final String myPrefix = nsPrefix;
        final String myUri = nsUri;
        xpath.setNamespaceContext(new NamespaceContext() {
            public String getNamespaceURI(String prefix) {
                return myPrefix.equals(prefix) ? myUri : null;
            }

            public String getPrefix(String namespaceURI) {
                return null; // we are not using this.
            }

            public Iterator<?> getPrefixes(String namespaceURI) {
                return null; // we are not using this.
            }
        });
    }

    XPathExpression expr = xpath.compile(xpathExpression);
    NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

    List<String> lines = new ArrayList<>();

    for (int i = 0; i < nodes.getLength(); i++) {
        lines.add((indenting(nodes.item(i))));
    }

    return lines.toArray(new String[lines.size()]);

}

From source file:Main.java

@SuppressWarnings("UseSpecificCatch")
public static boolean saveXML(Document doc, File outfile, boolean indent) {
    try {/* w w w .  j  av a 2  s  . c  o m*/
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new OutputStreamWriter(new FileOutputStream(outfile), "UTF-8"));
        if (indent) {
            XPathFactory xpathFactory = XPathFactory.newInstance();
            // XPath to find empty text nodes.
            XPathExpression xpathExp = xpathFactory.newXPath().compile("//text()[normalize-space(.) = '']");
            NodeList emptyTextNodes = (NodeList) xpathExp.evaluate(doc, XPathConstants.NODESET);

            // Remove each empty text node from document.
            for (int i = 0; i < emptyTextNodes.getLength(); i++) {
                Node emptyTextNode = emptyTextNodes.item(i);
                emptyTextNode.getParentNode().removeChild(emptyTextNode);
            }
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        }
        transformer.transform(source, result);
        return true;
    } catch (Exception ex) {
        return false;
    }
}

From source file:com.github.radium226.github.maven.MetaDataDownloader.java

public static String evaluateXPath(InputStream pomInputStream, String expression)
        throws XPathExpressionException {
    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xPath = xPathFactory.newXPath();
    xPath.setNamespaceContext(new NamespaceContext() {

        @Override//w  ww  . j ava2 s .c om
        public String getNamespaceURI(String prefix) {
            if (prefix.equals("ns")) {
                return "http://maven.apache.org/POM/4.0.0";
            }

            return null;
        }

        @Override
        public String getPrefix(String namespaceURI) {
            return null;
        }

        @Override
        public Iterator getPrefixes(String namespaceURI) {
            return null;
        }
    });
    XPathExpression xPathExpression = xPath.compile(expression);
    String version = (String) xPathExpression.evaluate(new InputSource(pomInputStream), XPathConstants.STRING);
    return version;
}

From source file:Main.java

@GuardedBy("xpathFactoryLock")
public static XPath createNewXPathInstance() {
    XPathFactory factory = null;

    xpathFactoryLock.lock();/*  ww w.j  av  a 2  s. co m*/
    try {
        factory = XPathFactory.newInstance();
    } finally {
        xpathFactoryLock.unlock();
    }

    return factory.newXPath();
}

From source file:com.wso2telco.identity.application.authentication.endpoint.util.ReadMobileConnectConfig.java

public static Map<String, String> query(String XpathExpression) {

    Map<String, String> ConfigfileAttributes = new Hashtable<String, String>();

    // standard for reading an XML file
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);/*from w  w w . ja v a2 s  . co  m*/
    DocumentBuilder builder;
    Document doc = null;
    XPathExpression expr = null;
    try {
        builder = factory.newDocumentBuilder();
        doc = builder.parse(CarbonUtils.getCarbonConfigDirPath() + File.separator + "mobile-connect.xml");

        // create an XPathFactory
        XPathFactory xFactory = XPathFactory.newInstance();

        // create an XPath object
        XPath xpath = xFactory.newXPath();

        // compile the XPath expression
        expr = xpath.compile("//" + XpathExpression + "/*");
        // run the query and get a nodeset
        Object result = expr.evaluate(doc, XPathConstants.NODESET);
        //        // cast the result to a DOM NodeList
        NodeList nodes = (NodeList) result;

        for (int i = 0; i < nodes.getLength(); i++) {
            ConfigfileAttributes.put(nodes.item(i).getNodeName(), nodes.item(i).getTextContent());
        }
    } catch (SAXException e) {
        log.error(e.getMessage());
    } catch (IOException e) {
        log.error(e.getMessage());
    } catch (ParserConfigurationException e) {
        log.error(e.getMessage());
    } catch (XPathExpressionException e) {
        log.error(e.getMessage());
    }

    return ConfigfileAttributes;
}