XML parsing in java with xpath

笑着哭i 提交于 2019-11-29 17:26:53

Try something like this:

private static final DocumentBuilderFactory DOCUMENT_BUILDER_FACTORY = DocumentBuilderFactory.newInstance();
private static final XPathFactory XPATH_FACTORY = XPathFactory.newInstance();

public static void parseXml(String urlPath) throws Exception {
    URL url = new URL(urlPath);
    URLConnection connection = url.openConnection();
    DocumentBuilder db = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder();

    final Document document = db.parse(connection.getInputStream());
    XPath xPathEvaluator = XPATH_FACTORY.newXPath();

    NodeList tracksinfoNodes = (NodeList) xPathEvaluator.compile("lfm/results/trackmatches/track").evaluate(
            document, XPathConstants.NODESET);
    for (int i = 0; i < tracksinfoNodes.getLength(); i++) {
        Node trackNameNode = tracksinfoNodes.item(i);

        NodeList childs = trackNameNode.getChildNodes();

        for (int j = 0; j < childs.getLength(); j++) {
            Node n = childs.item(j);

            if (!n.getNodeName().equals("#text")) {
                System.out.println(String.format("%s: %s", n.getNodeName(), n.getTextContent()));   
            }
        }

        System.out.println("==============");
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!