Example usage for javax.xml.xpath XPath evaluate

List of usage examples for javax.xml.xpath XPath evaluate

Introduction

In this page you can find the example usage for javax.xml.xpath XPath evaluate.

Prototype

public Object evaluate(String expression, InputSource source, QName returnType) throws XPathExpressionException;

Source Link

Document

Evaluate an XPath expression in the context of the specified InputSource and return the result as the specified type.

Usage

From source file:br.gov.lexml.parser.documentoarticulado.LexMLUtil.java

public static String formatLexML(String xml) {
    String retorno = null;/*from   w ww.  j  a  va 2 s  .co m*/
    try {
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8"))));

        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);
        }

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

        StringWriter stringWriter = new StringWriter();
        StreamResult streamResult = new StreamResult(stringWriter);

        transformer.transform(new DOMSource(document), streamResult);

        retorno = stringWriter.toString();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return retorno;

}

From source file:Main.java

public static String toPrettyString(String xml) {
    int indent = 4;
    try {/*from   w  w  w  . ja va  2s  .c o m*/
        // Turn xml string into a document
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8"))));

        // Remove whitespaces outside tags
        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);
        }

        // Setup pretty print options
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", indent);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");

        // Return pretty print xml string
        StringWriter stringWriter = new StringWriter();
        transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
        return stringWriter.toString();
    } catch (Exception e) {
        System.out.println(xml);
        throw new RuntimeException(
                "Problems prettyfing xml content [" + Splitter.fixedLength(100).split(xml) + "]", e);
    }
}

From source file:de.dplatz.padersprinter.control.TripService.java

static boolean isNodePresent(Node node, String expr, XPath xpath) throws XPathExpressionException {
    return xpath.evaluate(expr, node, XPathConstants.NODE) != null;
}

From source file:eu.planets_project.tb.utils.XCDLParser.java

/**
 * //from w w w .jav  a 2  s. c om
 * @param xcdlDoc
 * @return
 * @throws XPathExpressionException
 */
public static List<MeasurementImpl> parseXCDL(Document xcdlDoc) throws XPathExpressionException {
    List<MeasurementImpl> props = new Vector<MeasurementImpl>();

    XPath xpath = XPathFactory.newInstance().newXPath();
    NodeList nodes = (NodeList) xpath.evaluate("/*//property", xcdlDoc, XPathConstants.NODESET);

    for (int i = 0; i < nodes.getLength(); i++) {
        Node n = nodes.item(i);
        String name = (String) xpath.evaluate("./name", n, XPathConstants.STRING);
        String id = (String) xpath.evaluate("./name/@id", n, XPathConstants.STRING);
        // Loop through the property definitions and patch them into Property objects.
        MeasurementImpl m = new MeasurementImpl(makePropertyUri(id, name),
                (String) xpath.evaluate("./valueSet/labValue/val", n, XPathConstants.STRING));
        // FIXME Unify this construction: See also XCDLService.createPropertyFromFFProp
        //            m.setType( "xcdl:" + (String) xpath.evaluate( "./valueSet/labValue/type", n,  XPathConstants.STRING) );

        props.add(m);
    }

    return props;
}

From source file:de.dplatz.padersprinter.control.TripService.java

static Node getNode(Node node, String expr, XPath xpath) throws XPathExpressionException {
    return (Node) xpath.evaluate(expr, node, XPathConstants.NODE);
}

From source file:Main.java

/**
 * getStringListFromXPath//from   w w w .  ja  v a2  s  . c o  m
 * Gets a list of strings from an xml.
 * @param rootNodeExpression Evaluated on the root of the sqlconfig document to get a single Node.
 * @param listExpression Evaluated on the Node returned by rootNodeExpression, gets a NodeList.
 * @return A list of the text contents of the NodeList returned by evaluating the listExpression.
 */
public static List<String> getStringListFromXPath(Document doc, XPath xpath, String rootNodeExpression,
        String listExpression) {
    synchronized (xpath) {
        try {
            return getStringListFromXPath((Node) xpath.evaluate(rootNodeExpression, doc, XPathConstants.NODE),
                    xpath, listExpression);
        } catch (Exception e) {
            System.err.println("Error evaluating xpath expression: " + rootNodeExpression);
            e.printStackTrace();
        }
        return new Vector<String>();
    }
}

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

/**
 * @param nifiTemplate the nifi template xml string
 * @return the name of the template/* w ww . j a va 2  s  .c om*/
 */
public static String getTemplateName(String nifiTemplate)
        throws ParserConfigurationException, XPathExpressionException, IOException, SAXException {

    XPathFactory xpathFactory = XPathFactory.newInstance();
    XPath xpath = xpathFactory.newXPath();

    InputSource source = new InputSource(new StringReader(nifiTemplate));
    String name = (String) xpath.evaluate("/template/name", source, XPathConstants.STRING);
    return name;
}

From source file:de.dplatz.padersprinter.control.TripService.java

static String parseStringNode(Node node, String expr, XPath xpath) throws XPathExpressionException {
    String val = (String) xpath.evaluate(expr, node, XPathConstants.STRING);
    val = StringEscapeUtils.unescapeHtml4(val);
    return val;
}

From source file:de.dplatz.padersprinter.control.TripService.java

static int parseIntegerNode(Node node, String expr, XPath xpath) throws XPathExpressionException {
    return Integer.parseInt((String) xpath.evaluate(expr, node, XPathConstants.STRING));
}

From source file:com.cloudseal.spring.client.namespace.Utility.java

public static void removeNode(final Element rootElement, final String xPathLocation)
        throws XPathExpressionException {
    final XPath xPath = XPathFactory.newInstance().newXPath();
    xPath.setNamespaceContext(new CloudSealNamespaceContext());
    final Node node = (Node) xPath.evaluate(xPathLocation, rootElement, XPathConstants.NODE);
    final short nodeType = node.getNodeType();

    switch (nodeType) {
    case Node.ELEMENT_NODE:
        final Node parent = node.getParentNode();
        parent.removeChild(node);/*from  ww  w.j  a va2s  .  co m*/
        break;

    case Node.ATTRIBUTE_NODE:
        final Attr attribute = (Attr) node;
        final Element element = attribute.getOwnerElement();
        element.removeAttributeNode(attribute);
        break;

    default:
        throw new IllegalArgumentException("Not supported node type: " + nodeType);
    }
}