使用JDK自身的功能解析XML文件

try {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    Document doc = builder.parse(new FileInputStream(file.getName()));
    XPathFactory f = XPathFactory.newInstance();
    XPath path = f.newXPath();
    Node ack = (Node) path.evaluate("/SalesReportAcknowledgementNotification/SalesReportAcknowledgment/Comment", doc, XPathConstants.NODE);
                    
    InputOutput io = IOProvider.getDefault().getIO("提交信息:", false);
    io.getOut().print("处理结果:"+ ack.getTextContent()+"\n");
    io.getOut().close();
                    
} catch (SAXException e) {
    System.err.println(e.getMessage());
} catch (XPathExpressionException ex) {
    Exceptions.printStackTrace(ex);
} catch (ParserConfigurationException ex) {
    Exceptions.printStackTrace(ex);
}

惊喜的发现:

根本不用考虑命名空间问题,直接使用不含命名空间的xpath表达式就可以定位文档,非常方便。

你可能感兴趣的:(xml)