即使解析了XML,Document.toString()也是“[#document:null]”

时间:2014-08-09 22:59:07

标签: java xml

考虑这个例子

@Test
    public void testXML() {
        final String s = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><results>\n" +
                "    <status>OK</status>\n" +
                "    <usage>By accessing AlchemyAPI or using information generated by AlchemyAPI, you are agreeing to be bound by the AlchemyAPI Terms of Use: http://www.alchemyapi.com/company/terms.html</usage>\n" +
                "    <url/>\n" +
                "    <language>english</language>\n" +
                "    <docSentiment>\n" +
                "        <type>neutral</type>\n" +
                "    </docSentiment>\n" +
                "</results> ";

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder;
        try
        {
            builder = factory.newDocumentBuilder();
            Document doc = builder.parse( new InputSource( new StringReader( s ) ) );
            System.out.println(doc.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

当我运行这个例子时 System.out.println(doc.toString());原来是[#document: null]

我也在线验证了这个XML,没有发现任何错误。我错过了什么?

我需要什么?

我需要在此<docSentiment>

中找出XML的值

由于

1 个答案:

答案 0 :(得分:2)

根据MadProgrammer的建议,我设法得到了值

@Test
public void testXML() {
    final String s = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><results>\n" +
            "    <status>OK</status>\n" +
            "    <usage>By accessing AlchemyAPI or using information generated by AlchemyAPI, you are agreeing to be bound by the AlchemyAPI Terms of Use: http://www.alchemyapi.com/company/terms.html</usage>\n" +
            "    <url/>\n" +
            "    <language>english</language>\n" +
            "    <docSentiment>\n" +
            "        <type>neutral</type>\n" +
            "    </docSentiment>\n" +
            "</results>";

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    try
    {
        builder = factory.newDocumentBuilder();
        Document doc = builder.parse( new InputSource( new StringReader( s ) ) );

        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();
        XPathExpression expr = xpath.compile("//docSentiment/type");
        NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
        System.out.println("Sentiment:" + ((DTMNodeList) nl).getDTMIterator().toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

我输出

Sentiment:neutral