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

/**
 * Evaluates the XPath expression against the <code>xml</code> and returns the selected value.
 * /* w w  w .j av a2 s .  c om*/
 * @param expression Expression to evaluate.
 * @param xml The xml to query.
 * @return The selected value.
 * @throws XPathExpressionException If an error occurs evaluating the expression.
 */
public static String getValue(final String expression, final String xml) throws XPathExpressionException {
    final InputSource source = new InputSource(new StringReader(xml));
    final XPathFactory factory = XPathFactory.newInstance();
    final XPath xpath = factory.newXPath();

    return xpath.evaluate(expression, source);
}

From source file:Main.java

/**
 * Evaluates given XPath expression and returns node list. 
 * @param expr XPath expression//from  w ww  .j av a  2  s .  co  m
 * @param fileName path of the XML file to be parsed
 * @return 
 * @throws XPathExpressionException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 */
public static NodeList getNodeList(final String expr, final File xmlFile)
        throws XPathExpressionException, ParserConfigurationException, SAXException, IOException {

    XPath xPath = XPathFactory.newInstance().newXPath();
    NodeList nodeList = (NodeList) xPath.evaluate(expr, parseXMLFile(xmlFile), XPathConstants.NODESET);

    return nodeList;
}

From source file:Main.java

static public ArrayList<Element> selectElements(Element element, String xpathExpression)
        throws XPathExpressionException {
    ArrayList<Element> resultVector = new ArrayList<Element>();
    if (element == null) {
        return resultVector;
    }//from w w  w. j  a v  a  2 s.c o m
    if (xpathExpression.indexOf("/") == -1) {
        NodeList nodeList = element.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE && node.getNodeName().equals(xpathExpression)) {
                resultVector.add((Element) node);
            }
        }
    } else {
        XPath xpath = XPathFactory.newInstance().newXPath();
        NodeList nodes = (NodeList) xpath.evaluate(xpathExpression, element, XPathConstants.NODESET);

        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            resultVector.add((Element) node);
        }
    }
    return resultVector;
}

From source file:Main.java

static public Element selectSingleElement(Element element, String xpathExpression)
        throws XPathExpressionException {
    if (xpathExpression.indexOf("/") == -1) {
        NodeList nodeList = element.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE && node.getNodeName().equals(xpathExpression)) {
                return (Element) node;
            }/*from  w w w .j a v  a  2  s. com*/
        }
        //  NodeList nodes = element.getElementsByTagName(xpathExpression);
        //  if (nodes.getLength() > 0) {
        //      return (Element) nodes.item(0);
        //  } else {
        return null;
        //  }
    } else {
        XPath xpath = XPathFactory.newInstance().newXPath();
        Element node = (Element) xpath.evaluate(xpathExpression, element, XPathConstants.NODE);
        return node;
    }
}

From source file:Main.java

/**
 * Gets the object at the given XPath in the given XML node. See also:
 * {@link #evalXPath(String, String, javax.xml.namespace.QName)}.
 *
 * @param d the node to look in/*  ww w. j  ava2s  .c o  m*/
 * @param expr the XPath expression to evaluate
 * @param returnType the expected return type of the object
 * @return the object at the specified XPath in the node
 * @throws XPathExpressionException if an error occurs processing the XPath
 * expression
 */
static Object evalXPath(Node d, String expr, QName returnType) throws XPathExpressionException {
    return XPathFactory.newInstance().newXPath().compile(expr).evaluate(d, returnType);
}

From source file:Main.java

@SuppressWarnings("UseSpecificCatch")
public static boolean saveXML(Document doc, File outfile, boolean indent) {
    try {//from  ww  w.  java 2s. 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:Main.java

/** Builds an XPath. This is identical to calling
 *  <tt>XPathFactory.newInstance().newXPath().compile(expression)</tt> except
 *  that rather than throwing an {@link XPathExpressionException} it throws an
 *  {@link AssertionError}. <br>//from w w w . j a  v  a  2 s.  co m
 *  <br>
 *  This is intended for use with pre-defined XPaths stored as constants,
 *  where runtime exceptions should not be possible.
 *  @param expression The XPath expression to compile.
 *  @throws AssertionError If the nested call to <tt>XPath.newInstance(path)</tt>
 *                         throws an {@link XPathExpressionException}.
 */
public static synchronized XPathExpression xpath(String expression) {
    if (xPath == null)
        xPath = XPathFactory.newInstance().newXPath();

    try {
        return xPath.compile(expression);
    } catch (XPathExpressionException e) {
        throw new AssertionError("Error initializing XPath instance for '" + expression + "': " + e);
    }
}

From source file:com.thoughtworks.go.util.XpathUtils.java

public static boolean nodeExists(InputSource inputSource, String xpath) throws XPathExpressionException {
    XPathFactory factory = XPathFactory.newInstance();
    XPathExpression expression = factory.newXPath().compile(xpath);
    Boolean b = (Boolean) expression.evaluate(inputSource, XPathConstants.BOOLEAN);
    return b != null && b;
}

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

/**
 * /*from  w  w w. ja v  a2 s. co m*/
 * @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:Main.java

/**
 * Returns a new instance of XPath, which is not thread safe and not
 * reentrant./*from  w  w  w.java2  s  .c  o m*/
 */
public static XPath xpath() {
    return XPathFactory.newInstance().newXPath();
}