Example usage for javax.xml.xpath XPath compile

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

Introduction

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

Prototype

public XPathExpression compile(String expression) throws XPathExpressionException;

Source Link

Document

Compile an XPath expression for later evaluation.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    Document doc = factory.newDocumentBuilder()
            .parse("http://stackoverflow.com/feeds/tag?tagnames=java&sort=newest");
    Element root = doc.getDocumentElement();
    XPath xPath = XPathFactory.newInstance().newXPath();
    XPathExpression expression = xPath.compile("//entry");
    NodeList nl = (NodeList) expression.evaluate(root, XPathConstants.NODESET);
    System.out.println("Found " + nl.getLength() + " items...");
    for (int index = 0; index < nl.getLength(); index++) {
        Node node = nl.item(index);
        expression = xPath.compile("title");
        Node child = (Node) expression.evaluate(node, XPathConstants.NODE);
        System.out.println(child.getTextContent());
    }/*w ww.ja  va  2  s. c o  m*/
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    DocumentBuilderFactory Factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = Factory.newDocumentBuilder();
    Document doc = builder.parse("myxml.xml");
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();

    XPathExpression expr = xpath.compile("//" + "item1" + "/*");
    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;
    System.out.println(nodes.getLength());
    for (int i = 0; i < nodes.getLength(); i++) {
        Element el = (Element) nodes.item(i);
        System.out.println("tag: " + el.getNodeName());
        if (el.getFirstChild().getNodeType() == Node.TEXT_NODE)
            System.out.println("inner value:" + el.getFirstChild().getNodeValue());

        NodeList children = el.getChildNodes();
        for (int k = 0; k < children.getLength(); k++) {
            Node child = children.item(k);
            if (child.getNodeType() != Node.TEXT_NODE) {
                System.out.println("child tag: " + child.getNodeName());
                if (child.getFirstChild().getNodeType() == Node.TEXT_NODE)
                    System.out.println("inner child value:" + child.getFirstChild().getNodeValue());
            }/*from   w  w w. j  a  v  a2s  .com*/
        }
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {

    String xml = "<metadata><codes class = 'class1'>" + "<code code='ABC'>" + "<detail x='blah blah'/>"
            + "</code>" + "</codes>" + "<codes class = 'class2'>" + "<code code = '123'>"
            + "<detail x='blah blah'/></code></codes></metadata>";

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(new ByteArrayInputStream(xml.getBytes()));

    XPath xPath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xPath.compile("//codes/code[@code ='ABC']");
    Object result = expr.evaluate(doc, XPathConstants.NODESET);

    NodeList nodes = (NodeList) result;
    System.out.println(nodes.getLength() > 0 ? "Yes" : "No");
    for (int i = 0; i < nodes.getLength(); i++) {
        System.out.println("nodes: " + nodes.item(i).getNodeValue());
    }/*from  www.jav  a2  s  .  c om*/
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(false); // never forget this!
    DocumentBuilder builder = factory.newDocumentBuilder();

    Document doc = builder.parse("/data.xml");

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

    XPathExpression xPathExpression = xpath.compile("//city/text()");

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

    System.out.println(result.toString());

    NodeList nodes = (NodeList) result;

    System.out.println(nodes.getLength());
    for (int i = 0; i < nodes.getLength(); i++) {
        System.out.println(nodes.item(i).getNodeValue());
    }// ww  w. ja  v a  2s.c o  m
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    String exp = "/configs/markets/market";
    String path = "data.xml";

    Document xmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(path);

    XPath xPath = XPathFactory.newInstance().newXPath();
    XPathExpression xPathExpression = xPath.compile(exp);
    NodeList nodes = (NodeList) xPathExpression.evaluate(xmlDocument, XPathConstants.NODESET);

    Document newXmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    Element root = newXmlDocument.createElement("root");
    newXmlDocument.appendChild(root);/*from  w  w  w . j  a  va 2  s.  c  om*/
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        Node copyNode = newXmlDocument.importNode(node, true);
        root.appendChild(copyNode);
    }
    printXmlDocument(newXmlDocument);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(new File("Table.xml"));

    XPathFactory xFactory = XPathFactory.newInstance();
    XPath path = xFactory.newXPath();
    XPathExpression exp = path.compile("/tables/table");
    NodeList nlTables = (NodeList) exp.evaluate(doc, XPathConstants.NODESET);
    for (int tblIndex = 0; tblIndex < nlTables.getLength(); tblIndex++) {
        Node table = nlTables.item(tblIndex);
        Node nAtt = table.getAttributes().getNamedItem("title");
        System.out.println(nAtt.getTextContent());
        exp = path.compile("headings/heading");
        NodeList nlHeaders = (NodeList) exp.evaluate(table, XPathConstants.NODESET);
        Set<String> headers = new HashSet<String>(25);
        for (int index = 0; index < nlHeaders.getLength(); index++) {
            headers.add(nlHeaders.item(index).getTextContent().trim());
        }//from w w w . ja  v  a2s .c  o  m
        for (String header : headers) {
            System.out.println(header);
        }
        exp = path.compile("tablebody/tablerow");
        NodeList nlRows = (NodeList) exp.evaluate(table, XPathConstants.NODESET);
        for (int index = 0; index < nlRows.getLength(); index++) {
            Node rowNode = nlRows.item(index);
            exp = path.compile("tablecell/item");
            NodeList nlValues = (NodeList) exp.evaluate(rowNode, XPathConstants.NODESET);
            List<String> values = new ArrayList<String>(25);
            for (int valueIndex = 0; valueIndex < nlValues.getLength(); valueIndex++) {
                values.add(nlValues.item(valueIndex).getTextContent().trim());
            }
            for (String value : values) {
                System.out.println(value);
            }
        }
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    XPathFactory xpf = XPathFactory.newInstance();
    XPath xp = xpf.newXPath();
    xp.setNamespaceContext(new MyNamespaceContext());
    XPathExpression xpe = xp.compile("ns:feed/ns:entry");
    FileInputStream xmlStream = new FileInputStream("input.xml");
    InputSource xmlInput = new InputSource(xmlStream);
    Element result = (Element) xpe.evaluate(xmlInput, XPathConstants.NODE);
    System.out.println(result);/*from  ww  w  .  j av a  2 s . co  m*/
}

From source file:Main.java

public static void main(final String[] args) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);/*from  www.j a v a 2 s  .c o  m*/
    DocumentBuilder builder = factory.newDocumentBuilder();

    Document doc = builder.parse(new ByteArrayInputStream(( //
    "<?xml version=\"1.0\"?>" + //
            "<people>" + //
            "<person><name>First Person Name</name></person>" + //
            "<person><name>Second Person Name</name></person>" + //
            "</people>" //
    ).getBytes()));

    String fragment = "<name>Changed Name</name>";
    Document fragmentDoc = builder.parse(new ByteArrayInputStream(fragment.getBytes()));

    Node injectedNode = doc.adoptNode(fragmentDoc.getFirstChild());

    XPath xPath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xPath.compile("//people/person[2]/name");
    Element nodeFound = (Element) expr.evaluate(doc, XPathConstants.NODE);

    Node parentNode = nodeFound.getParentNode();
    parentNode.removeChild(nodeFound);
    parentNode.appendChild(injectedNode);

    DOMSource domSource = new DOMSource(doc);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    StreamResult result = new StreamResult(new StringWriter());
    transformer.transform(domSource, result);
    System.out.println(result.getWriter().toString());
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = db.parse(new InputSource(new StringReader("<root>\r\n" + //
            "<Users>\r\n" + //
            "   <App id=\"test\">\r\n" + //
            "      <Username>ADMIN</Username>\r\n" + //
            "      <Password>ADMIN</Password>\r\n" + //
            "   </App>\r\n" + //
            "</Users>\r\n" + //
            "<Users>\r\n" + //
            "   <App id=\"test2\">\r\n" + //
            "      <Username>ADMIN2</Username>\r\n" + //
            "      <Password>ADMIN2</Password>\r\n" + //
            "   </App>\r\n" + //
            "</Users>\r\n" + //
            "</root>")));
    String inputId = "test2";
    String xpathStr = "//Users/App[@id='" + inputId + "']";
    // retrieve elements and change their content
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xpath.compile(xpathStr + "/Username");
    Node username = (Node) expr.evaluate(doc, XPathConstants.NODE);
    username.setTextContent("test-username");
    expr = xpath.compile(xpathStr + "/Password");
    Node password = (Node) expr.evaluate(doc, XPathConstants.NODE);
    password.setTextContent("test-password");
    // output the document
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    StringWriter writer = new StringWriter();
    transformer.transform(new DOMSource(doc), new StreamResult(writer));
    System.out.println(writer.toString());

}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    SimpleDateFormat xmlDateFormat = new SimpleDateFormat("MM.dd.yy");

    MapVariableResolver resolver = new MapVariableResolver();
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = dbf.newDocumentBuilder();
    Document document = builder.parse(new File("t.xml"));

    XPathFactory factory = XPathFactory.newInstance();
    XPath xPath = factory.newXPath();
    xPath.setXPathVariableResolver(resolver);
    XPathExpression expression = xPath.compile("/schedule/show[@date=$date]/guest");

    String formattedDate = xmlDateFormat.format(new Date(2006, 5, 14));
    resolver.addVariable(null, "date", formattedDate);
    Element guest = (Element) expression.evaluate(document, XPathConstants.NODE);

    System.out.println(guest.getElementsByTagName("name").item(0).getTextContent());
}