简体   繁体   English

在Java中使用XPath进行XML解析

[英]XML parsing using XPath in Java

Hi! 嗨! I've spent some time to parse an XML document with XPath. 我花了一些时间用XPath解析XML文档。 It seeams to be a simple task but I got in troubles since the begining. 这似乎是一个简单的任务,但是自从一开始我就遇到了麻烦。 My code is : 我的代码是:

public class QueryXML3 {

    public static void main(String[] args) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder;
        Document doc = null;

        try {
            builder = factory.newDocumentBuilder();
            //doc = builder.parse("SampleExample.xml");
            InputStream is = QueryXML3.class.getClassLoader().getResourceAsStream("SampleXml.xml");
            doc = builder.parse(is);

            XPathFactory xpathFactory = XPathFactory.newInstance();

            // Create XPath object
            XPath xpath = xpathFactory.newXPath();


            Node parNode = getParameterNode(doc, xpath);
            System.out.println("parameter node:" + parNode);

            NodeList res = getParameterNodeList(doc, xpath );
            System.out.println("List of nodes" + res);



        } catch (ParserConfigurationException | SAXException | IOException e) {
            e.printStackTrace();
        }

    }

    public static Node getParameterNode(Document doc, XPath xpath) {
        Node res = null;
        try {
            res = (Node) xpath.evaluate("/definitions/process", doc, XPathConstants.NODE);

        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }
        return res;
    }

    public static NodeList getParameterNodeList(Document doc, XPath xpath) {
        NodeList nodeList = null;
        try {
            nodeList = (NodeList) xpath.evaluate("/definitions/process", doc, XPathConstants.NODESET);

            for (int i = 0; i > nodeList.getLength(); i++) {
                System.out.print(nodeList.item(i).getNodeName() + " ");
            }

        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }
        return nodeList;
    }
}

As a result i get this: 结果我得到这个:

parameter node:[process: null] List of nodes com.sun.org.apache.xml.internal.dtm.ref.DTMNodeList@2f17aadf 参数node:[process:null]节点列表com.sun.org.apache.xml.internal.dtm.ref.DTMNodeList@2f17aadf

I just want to output all the nodes of my xml file and theire attributes... 我只想输出我的xml文件和theire属性的所有节点...

You are really asking how to serialize an Element to a string - use either a Transformer or DOMImplementationLS . 您实际上是在问如何将Element序列化为字符串-使用Transformer或DOMImplementationLS

The NodeList type has no toString() contract and the implementation does not override the default Object.toString() . NodeList类型没有toString()协定,并且实现不覆盖默认的Object.toString() You need to iterate over the nodes and serialize each Element as above. 您需要遍历节点并如上所述序列化每个Element

You could easily parse an XML file in java using a 3rd party package such as JSoup or JDom . 您可以使用第3方软件包(例如JSoupJDom)轻松地在Java中解析XML文件。

As an example, here is some simple output of an XML files elements using JSoup: 例如,这是使用JSoup的XML文件元素的一些简单输出:

<note>
   <to>Tove</to>
   <from>Jani</from>
   <heading>Reminder</heading>
   <body>Don't forget me this weekend!</body>
</note>

Java code printing all elements and the selected <from> -element: Java代码打印所有元素和选定的<from> -element:

String xml = "<note>\n"
        + "<to>Tove</to>\n"
        + "<from>Jani</from>\n"
        + "<heading>Reminder</heading>\n"
        + "<body>Don't forget me this weekend!</body>\n"
        + "</note>";
Document doc = Jsoup.parse(xml, "", Parser.xmlParser());
for (Element e : doc.children()) {
    System.out.println(e);
}

Element fromElement = doc.select("from").first();

System.out.println("\nThis is the <from>-element content:\n" + fromElement);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM