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

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   ww w .  j  a  v a  2s . c om*/
        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:MainClass.java

public static void main(String[] args) throws ParserConfigurationException, XPathExpressionException,
        org.xml.sax.SAXException, java.io.IOException {
    String documentName = args[0];
    String expression = args[1];/*w w w  . j av a  2  s .com*/

    DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = parser.parse(new java.io.File(documentName));

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

    System.out.println(xpath.evaluate(expression, doc));

    NodeList nodes = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET);
    for (int i = 0, n = nodes.getLength(); i < n; i++) {
        Node node = nodes.item(i);
        System.out.println(node);
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);//w ww . j  a  va2 s . c  o  m
    DocumentBuilder builder;
    Document doc = null;
    builder = factory.newDocumentBuilder();
    doc = builder.parse("employees.xml");
    // Create XPathFactory object
    XPathFactory xpathFactory = XPathFactory.newInstance();
    // Create XPath object
    XPath xpath = xpathFactory.newXPath();
    String name = getEmployeeNameById(doc, xpath, 4);
    System.out.println("Employee Name with ID 4: " + name);

    List<String> names = getEmployeeNameWithAge(doc, xpath, 30);
    System.out.println("Employees with 'age>30' are:" + Arrays.toString(names.toArray()));

    List<String> femaleEmps = getFemaleEmployeesName(doc, xpath);
    System.out.println("Female Employees names are:" + Arrays.toString(femaleEmps.toArray()));
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    Document retval = dbf.newDocumentBuilder().newDocument();
    Element parent = retval.createElement("parent");
    retval.appendChild(parent);/*from   w  w w.  j a va 2  s .co m*/

    Element child1 = retval.createElement("child");
    child1.setTextContent("child.text");
    parent.appendChild(child1);
    Element child2 = retval.createElement("child");
    child2.setTextContent("child.text.2");
    parent.appendChild(child2);

    XPathFactory factory = XPathFactory.newInstance();
    XPath xPath = factory.newXPath();
    System.out.println(xPath.evaluate("//child/text()", retval, XPathConstants.NODE).getClass());

}

From source file:Main.java

public static void main(String[] args)
        throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {

    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);//from  ww w . j ava2s .  c  om
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse("books.xml");

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    XPathExpression expr = xpath.compile("//numDocs");

    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;
    for (int i = 0; i < nodes.getLength(); i++) {
        System.out.println(nodes.item(i).getNodeValue());
    }
}

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   w  w w .  ja  v  a 2 s.  c o m*/
}

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

From source file:Main.java

public static void main(String[] args) throws Exception {
    List<String> names = new ArrayList<>();
    URL oracle = new URL("http://weather.yahooapis.com/forecastrss?w=2502265");
    InputStream is = oracle.openStream();
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);/*from  w  w w . ja  va2  s . co  m*/
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse(is);
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    XPathExpression expr = xpath.compile("//*:*/@*");
    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nl = (NodeList) result;
    for (int i = 0; i < nl.getLength(); i++) {
        names.add(nl.item(i).getNodeName());
        Node node = nl.item(i);
        String path = "." + node.getNodeName() + " = " + node.getNodeValue();
        node = ((Attr) node).getOwnerElement();
        while (node != null) {
            path = node.getNodeName() + '/' + path;
            node = node.getParentNode();
        }
        System.out.println(path);
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    String xml = "<?xml version='1.0' encoding='UTF-8'?>" + "<Employees>"
            + "  <Employee emplid='1' type='admin'>" + "    <firstname/>" + "    <lastname>A</lastname>"
            + "    <age>30</age>" + "    <email>j@s.com</email>" + "  </Employee>"
            + "  <Employee emplid='2' type='admin'>" + "    <firstname>S</firstname>"
            + "    <lastname>H</lastname>" + "    <age>32</age>" + "    <email>s@h.com</email>"
            + "  </Employee>" + "</Employees>";
    List<String> ids = Arrays.asList("1", "2");
    for (int i = 0; i < ids.size(); i++) {
        String employeeId = ids.get(i);
        String xpath = "/Employees/Employee[@emplid='" + employeeId + "']/firstname";
        XPath xPath = XPathFactory.newInstance().newXPath();
        String employeeFirstName = xPath.evaluate(xpath, new InputSource(new StringReader(xml)));
        if (employeeFirstName == "") {
            System.out.println("Employee " + employeeId + " has no first name.");
        } else {// w w  w  .  jav a 2 s .  c  o m
            System.out.println("Employee " + employeeId + "'s first name is " + employeeFirstName);
        }
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setValidating(false);// ww w  .j  av a 2 s  .c  o m
    domFactory.setNamespaceAware(true);
    domFactory.setIgnoringComments(true);
    domFactory.setIgnoringElementContentWhitespace(true);

    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document dDoc = builder.parse("C:/data.xsd");

    Node rootNode = dDoc.getElementsByTagName("xs:schema").item(0);
    System.out.println(rootNode.getNodeName());

    XPath xPath1 = XPathFactory.newInstance().newXPath();
    NamespaceContext nsContext = new NamespaceContext() {
        @Override
        public String getNamespaceURI(String prefix) {
            return "http://www.w3.org/2001/XMLSchema";
        }

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

        @Override
        public Iterator getPrefixes(String namespaceURI) {
            Set s = new HashSet();
            s.add("xs");
            return s.iterator();
        }
    };
    xPath1.setNamespaceContext((NamespaceContext) nsContext);
    NodeList nList1 = (NodeList) xPath1.evaluate("//xs:schema", dDoc, XPathConstants.NODESET);
    System.out.println(nList1.item(0).getNodeName());

    NodeList nList2 = (NodeList) xPath1.evaluate("//xs:element", rootNode, XPathConstants.NODESET);
    System.out.println(nList2.item(0).getNodeName());
}