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:Main.java

public static void main(String[] args) throws Exception {
    String source = "<p xmlns='http://www.java2s.com/nfe' versao='2.00'></p>";

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

    NamespaceContext context = new NamespaceContext() {
        String PREFIX = "nfe";
        String URI = "http://www.java2s.com/nfe";

        @Override/*from  w ww . j ava  2  s  . co m*/
        public String getNamespaceURI(String prefix) {
            return (PREFIX.equals(prefix)) ? URI : XMLConstants.NULL_NS_URI;
        }

        @Override
        public String getPrefix(String namespaceUri) {
            return (URI.equals(namespaceUri)) ? PREFIX : XMLConstants.DEFAULT_NS_PREFIX;
        }

        @Override
        public Iterator getPrefixes(String namespaceUri) {
            return Collections.singletonList(this.getPrefix(namespaceUri)).iterator();
        }
    };
    xPath.setNamespaceContext(context);
    InputSource inputSource = new InputSource(new StringReader(source));
    String versao = xPath.evaluate("//nfe:p/@versao", inputSource);
    System.out.println(versao.toString());
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xPath = factory.newXPath();
    SimpleNamespaceContext nsContext = new SimpleNamespaceContext();
    nsContext.addNamespace("s", "uri:test:schedule");
    xPath.setNamespaceContext(nsContext);

    String result = xPath.evaluate("/s:schedule/@name", new InputSource(new FileReader("t.xml")));
    System.out.println(result);/*from   w  w  w .jav  a 2 s. co  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(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 . co  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:ExtensionFunctionResolver.java

public static void main(String[] args) throws Exception {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();

    // set the NamespaceContext to 
    // org.apache.xalan.extensions.ExtensionNamespaceContext
    xpath.setNamespaceContext(new ExtensionNamespaceContext());

    // set the XPathFunctionResolver to 
    // org.apache.xalan.extensions.XPathFunctionResolverImpl
    xpath.setXPathFunctionResolver(new XPathFunctionResolverImpl());

    Object result = null;//from   ww  w  .ja  v  a2 s  .  c  om
    // Evaluate the XPath expression "math:max(/doc/num)" against 
    // the input document numlist.xml
    InputSource context = new InputSource("numlist.xml");
    result = xpath.evaluate(EXPR1, context, XPathConstants.NUMBER);
    System.out.println(EXPR1 + " = " + result);

    // Evaluate the XPath expression "java:ExtensionTest.test('Bob')"
    result = xpath.evaluate(EXPR2, context, XPathConstants.STRING);
    System.out.println(EXPR2 + " = " + result);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);/*from  w  w w .  j a  v  a2  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:Main.java

public static void main(String[] args) throws Exception {
    Main example = new Main();
    example.data.put("France", "Paris");
    example.data.put("Japan", "Tokyo");

    JAXBContext context = JAXBContext.newInstance(Main.class);
    Marshaller marshaller = context.createMarshaller();
    DOMResult result = new DOMResult();
    marshaller.marshal(example, result);

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

    Document document = (Document) result.getNode();
    XPathExpression expression = xpath.compile("//map/entry");
    NodeList nodes = (NodeList) expression.evaluate(document, XPathConstants.NODESET);

    expression = xpath.compile("//map");
    Node oldMap = (Node) expression.evaluate(document, XPathConstants.NODE);
    Element newMap = document.createElement("map");

    for (int index = 0; index < nodes.getLength(); index++) {
        Element element = (Element) nodes.item(index);
        newMap.setAttribute(element.getAttribute("key"), element.getAttribute("value"));
    }/* w w w  . j  a  va 2  s. co m*/

    expression = xpath.compile("//map/..");
    Node parent = (Node) expression.evaluate(document, XPathConstants.NODE);
    parent.replaceChild(newMap, oldMap);

    TransformerFactory.newInstance().newTransformer().transform(new DOMSource(document),
            new StreamResult(System.out));
}

From source file:XPathResolver.java

public static void main(String[] args) {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    // Set the NamespaceContext
    xpath.setNamespaceContext(new MyNamespaceContext());
    // Set the function resolver
    xpath.setXPathFunctionResolver(new MyFunctionResolver());
    // Set the variable resolver
    xpath.setXPathVariableResolver(new MyVariableResolver());

    Object result = null;/*from w  ww  . j a  v  a2s . c  o m*/
    try {
        result = xpath.evaluate(EXPR, (Object) null, XPathConstants.NUMBER);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // The evaluation result is 9.0.
    System.out.println("The evaluation result: " + result);
}

From source file:ApplyXPathJAXP.java

public static void main(String[] args) {
    QName returnType = null;//from   w w  w .  j a  va 2s . co m

    if (args.length != 3) {
        System.err.println("Usage: java ApplyXPathAPI xml_file xpath_expression type");
    }

    InputSource xml = new InputSource(args[0]);
    String expr = args[1];

    // set the return type
    if (args[2].equals("num"))
        returnType = XPathConstants.NUMBER;
    else if (args[2].equals("bool"))
        returnType = XPathConstants.BOOLEAN;
    else if (args[2].equals("str"))
        returnType = XPathConstants.STRING;
    else if (args[2].equals("node"))
        returnType = XPathConstants.NODE;
    else if (args[2].equals("nodeset"))
        returnType = XPathConstants.NODESET;
    else
        System.err.println("Invalid return type: " + args[2]);

    // Create a new XPath
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();

    Object result = null;
    try {
        // compile the XPath expression
        XPathExpression xpathExpr = xpath.compile(expr);

        // Evaluate the XPath expression against the input document
        result = xpathExpr.evaluate(xml, returnType);

        // Print the result to System.out.
        printResult(result);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:android.databinding.tool.MakeCopy.java

public static void main(String[] args) {
    if (args.length < 5) {
        System.out.println("required parameters: [-l] manifest adk-dir src-out-dir xml-out-dir "
                + "res-out-dir res-in-dir...");
        System.out.println("Creates an android data binding class and copies resources from");
        System.out.println("res-source to res-target and modifies binding layout files");
        System.out.println("in res-target. Binding data is extracted into XML files");
        System.out.println("and placed in xml-out-dir.");
        System.out.println("  -l          indicates that this is a library");
        System.out.println("  manifest    path to AndroidManifest.xml file");
        System.out.println("  src-out-dir path to where generated source goes");
        System.out.println("  xml-out-dir path to where generated binding XML goes");
        System.out.println("  res-out-dir path to the where modified resources should go");
        System.out.println(/*from w w w.j  a v a2s.  com*/
                "  res-in-dir  path to source resources \"res\" directory. One" + " or more are allowed.");
        System.exit(1);
    }
    final boolean isLibrary = args[0].equals("-l");
    final int indexOffset = isLibrary ? 1 : 0;
    final String applicationPackage;
    final int minSdk;
    final Document androidManifest = readAndroidManifest(new File(args[MANIFEST_INDEX + indexOffset]));
    try {
        final XPathFactory xPathFactory = XPathFactory.newInstance();
        final XPath xPath = xPathFactory.newXPath();
        applicationPackage = xPath.evaluate("string(/manifest/@package)", androidManifest);
        final Double minSdkNumber = (Double) xPath.evaluate("number(/manifest/uses-sdk/@android:minSdkVersion)",
                androidManifest, XPathConstants.NUMBER);
        minSdk = minSdkNumber == null ? 1 : minSdkNumber.intValue();
    } catch (XPathExpressionException e) {
        e.printStackTrace();
        System.exit(6);
        return;
    }
    final File srcDir = new File(args[SRC_INDEX + indexOffset], APP_SUBPATH);
    if (!makeTargetDir(srcDir)) {
        System.err.println("Could not create source directory " + srcDir);
        System.exit(2);
    }
    final File resTarget = new File(args[RES_OUT_INDEX + indexOffset]);
    if (!makeTargetDir(resTarget)) {
        System.err.println("Could not create resource directory: " + resTarget);
        System.exit(4);
    }
    final File xmlDir = new File(args[XML_INDEX + indexOffset]);
    if (!makeTargetDir(xmlDir)) {
        System.err.println("Could not create xml output directory: " + xmlDir);
        System.exit(5);
    }
    System.out.println("Application Package: " + applicationPackage);
    System.out.println("Minimum SDK: " + minSdk);
    System.out.println("Target Resources: " + resTarget.getAbsolutePath());
    System.out.println("Target Source Dir: " + srcDir.getAbsolutePath());
    System.out.println("Target XML Dir: " + xmlDir.getAbsolutePath());
    System.out.println("Library? " + isLibrary);

    boolean foundSomeResources = false;
    for (int i = RES_IN_INDEX + indexOffset; i < args.length; i++) {
        final File resDir = new File(args[i]);
        if (!resDir.exists()) {
            System.out.println("Could not find resource directory: " + resDir);
        } else {
            System.out.println("Source Resources: " + resDir.getAbsolutePath());
            try {
                FileUtils.copyDirectory(resDir, resTarget);
                addFromFile(resDir, resTarget);
                foundSomeResources = true;
            } catch (IOException e) {
                System.err.println("Could not copy resources from " + resDir + " to " + resTarget + ": "
                        + e.getLocalizedMessage());
                System.exit(3);
            }
        }
    }

    if (!foundSomeResources) {
        System.err.println("No resource directories were found.");
        System.exit(7);
    }
    processLayoutFiles(applicationPackage, resTarget, srcDir, xmlDir, minSdk, isLibrary);
}

From source file:com.semsaas.jsonxml.tools.JsonXpath.java

public static void main(String[] args) {
    /*/*  ww  w  .j  av  a2 s . c om*/
     * Process options
     */
    LinkedList<String> files = new LinkedList<String>();
    LinkedList<String> expr = new LinkedList<String>();
    boolean help = false;
    String activeOption = null;
    String error = null;

    for (int i = 0; i < args.length && error == null && !help; i++) {
        if (activeOption != null) {
            if (activeOption.equals("-e")) {
                expr.push(args[i]);
            } else if (activeOption.equals("-h")) {
                help = true;
            } else {
                error = "Unknown option " + activeOption;
            }
            activeOption = null;
        } else {
            if (args[i].startsWith("-")) {
                activeOption = args[i];
            } else {
                files.push(args[i]);
            }
        }
    }

    if (error != null) {
        System.err.println(error);
        showHelp();
    } else if (help) {
        showHelp();
    } else {
        try {
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();

            for (String f : files) {
                System.out.println("*** " + f + " ***");
                try {
                    // Create a JSON XML reader
                    XMLReader reader = XMLReaderFactory.createXMLReader("com.semsaas.jsonxml.JsonXMLReader");

                    // Prepare a reader with the JSON file as input
                    InputStreamReader stringReader = new InputStreamReader(new FileInputStream(f));
                    SAXSource saxSource = new SAXSource(reader, new InputSource(stringReader));

                    // Prepare a DOMResult which will hold the DOM of the xjson
                    DOMResult domResult = new DOMResult();

                    // Run SAX processing through a transformer
                    // (This could be done more simply, but we have here the opportunity to pass our xjson through
                    // an XSLT and get a legacy XML output ;) )
                    transformer.transform(saxSource, domResult);
                    Node dom = domResult.getNode();

                    XPathFactory xpathFactory = XPathFactory.newInstance();
                    for (String x : expr) {
                        try {
                            XPath xpath = xpathFactory.newXPath();
                            xpath.setNamespaceContext(new NamespaceContext() {
                                public Iterator getPrefixes(String namespaceURI) {
                                    return null;
                                }

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

                                public String getNamespaceURI(String prefix) {
                                    if (prefix == null) {
                                        return XJSON.XMLNS;
                                    } else if ("j".equals(prefix)) {
                                        return XJSON.XMLNS;
                                    } else {
                                        return null;
                                    }
                                }
                            });
                            NodeList nl = (NodeList) xpath.evaluate(x, dom, XPathConstants.NODESET);
                            System.out.println("-- Found " + nl.getLength() + " nodes for xpath '" + x
                                    + "' in file '" + f + "'");
                            for (int i = 0; i < nl.getLength(); i++) {
                                System.out.println(" +(" + i + ")+ ");
                                XMLJsonGenerator handler = new XMLJsonGenerator();
                                StringWriter buffer = new StringWriter();
                                handler.setOutputWriter(buffer);

                                SAXResult result = new SAXResult(handler);
                                transformer.transform(new DOMSource(nl.item(i)), result);

                                System.out.println(buffer.toString());
                            }
                        } catch (XPathExpressionException e) {
                            System.err.println("-- Error evaluating '" + x + "' on file '" + f + "'");
                            e.printStackTrace();
                        } catch (TransformerException e) {
                            System.err.println("-- Error evaluating '" + x + "' on file '" + f + "'");
                            e.printStackTrace();
                        }
                    }
                } catch (FileNotFoundException e) {
                    System.err.println("File '" + f + "' was not found");
                } catch (SAXException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TransformerException e) {
                    e.printStackTrace();
                }
            }
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        }
    }
}