• Java xpath example code THE RIGHT WAY


    http://www.xinotes.org/notes/note/1311/

    i have waste a afternoon time to find the java way to invoke xpath,

    java is evail

    Java xpath example code | Xinotes

        - Socrates
        Java xpath example code
        freyo

            Joined:
        07/27/2010
            Posts:
        122

        [Poor] [Fair] [Good] [Excellent] [Super!]  (Not rated)
        May 23, 2011 14:30:18    Last update: May 23, 2011 14:31:08
        There are two distinct ways to process XPath: with namespace and without namespace. The code is different depending on whether the parser is namespace aware.

            Code without namespace:

            import java.io.*;
            import javax.xml.parsers.*;
            import javax.xml.xpath.*;

            import org.w3c.dom.*;

            public class GetLicenseeName {
                public static void main(String[] args) throws Exception {
                if (args.length < 1) {
                    System.out.println("Usage: java GetLicenseeName <xml_file>");
                    return;
                }

                String xmlFile = args[0];

                DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
                InputStream in = new FileInputStream(xmlFile);
                Document doc = f.newDocumentBuilder().parse(in);
                in.close();

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

                NodeList nodes = (NodeList) xpath.evaluate(
                    "/test-license/licensee/name/text()",
                    doc,
                    XPathConstants.NODESET
                );
                System.out.println("Licensee name: " + nodes.item(0).getNodeValue());
                }
            }



            code with namespace:

            import java.io.*;
            import java.util.Iterator;
            import javax.xml.namespace.NamespaceContext;
            import javax.xml.parsers.*;
            import javax.xml.xpath.*;

            import org.w3c.dom.*;

            public class GetLicenseeNameNS {
                public static void main(String[] args) throws Exception {
                if (args.length < 1) {
                    System.out.println("Usage: java GetLicenseeNameNS <xml_file>");
                    return;
                }

                String xmlFile = args[0];

                DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
                // Now we are namespace aware!
                f.setNamespaceAware(true);
                InputStream in = new FileInputStream(xmlFile);
                Document doc = f.newDocumentBuilder().parse(in);
                in.close();

                XPath xpath = XPathFactory.newInstance().newXPath();
                xpath.setNamespaceContext(new NamespaceContext() {
                    public String getNamespaceURI(String prefix) {
                    // we know there's only one namespace uri, just return it!
                    return "http://www.notexisting.com/some_schema";
                    }

                    // this is not used by XPath
                    public String getPrefix(String namespaceURI) {
                    System.out.println("getPrefix: " + namespaceURI);
                    return null;
                    }

                    // this is not used by XPath
                    public Iterator getPrefixes(String namespaceURI) {
                    System.out.println("getPrefixes: " + namespaceURI);
                    return null;
                    }
                });

                String[] paths = {
                    "/test-license/licensee/name/text()",
                    "/p:test-license/p:licensee/p:name/text()",
                };

                for (String path: paths) {
                    NodeList nodes = (NodeList) xpath.evaluate(path, doc, XPathConstants.NODESET);
                    if (nodes.getLength() == 0) {
                    System.out.println(path + " does not work!");
                    }
                    else {
                    System.out.println(path + " works:");
                    System.out.println("Licensee name: " + nodes.item(0).getNodeValue());
                    }
                    System.out.println();
                }
                }
            }

            XML without namespace:

            <?xml version="1.0" encoding="UTF-8" standalone="no"?>
            <test-license>
                <licensee>
                <name>Paid in Full</name>
                <address>1234 Main. St.</address>
                </licensee>

                <product>
                <name>No use</name>
                </product>
            </test-license>

            XML with namespace:

            <?xml version="1.0" encoding="UTF-8" standalone="no"?>
            <test-license xmlns="http://www.notexisting.com/some_schema">
                <licensee>
                <name>Paid in Full</name>
                <address>1234 Main. St.</address>
                </licensee>

                <product>
                <name>No use</name>
                </product>
            </test-license>


        The same XPath expression works for both XML files when the parser is not namespace aware.

        When the parser is namespace aware, you have to adjust the XPath accordingly depending on whether the XML has namespace declarations: "/test-license/licensee/name/text()" works for the XML file without namespace, while "/p:test-license/p:licensee/p:name/text()" works for the XML file with namespace.
        Share |
        | Comment  | Tags
        

  • 相关阅读:
    JavaScript函数中的this四种绑定形式
    jQuery的html()、text()和val()的使用和区别
    iframe-父子-兄弟页面相互传值(jq和js两种方法)
    Spring Boot 嵌入式 Tomcat 文件上传、url 映射虚拟路径
    SpringMVC上传图片
    <iframe>和<frame>标签属性详解
    Mybatis 事物回滚最简单的操作方式
    SpringBoot配置log4j
    springboot整合redis(集群)
    Maven setting.xml简易配置
  • 原文地址:https://www.cnblogs.com/lexus/p/2358464.html
Copyright © 2020-2023  润新知