0

你好!我花了一些时间用 XPath 解析 XML 文档。这似乎是一项简单的任务,但从一开始我就遇到了麻烦。我的代码是:

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

结果我得到了这个:

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

我只想输出我的 xml 文件的所有节点及其属性...

4

2 回答 2

0

您真的在问如何将Element序列化为字符串 - 使用Transformer 或 DOMImplementationLS

NodeList类型没有契约并且toString()实现不会覆盖默认值Object.toString()。您需要遍历节点并Element如上所述序列化每个节点。

于 2013-11-13T11:13:38.930 回答
0

您可以使用JSoupJDom等 3rd 方包轻松解析 Java 中的 XML 文件。

例如,下面是使用 JSoup 的 XML 文件元素的一些简单输出:

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

打印所有元素和选定元素的 Java 代码<from>

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);
于 2013-11-13T11:19:39.887 回答