App下載
首頁javaxpathJava HTML/XML - 如何創(chuàng)建RSS FEED XML解析器

Java HTML/XML - 如何創(chuàng)建RSS FEED XML解析器

我們想知道如何創(chuàng)建RSS FEED XML解析器。
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
  public static void main(String[] args) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    Document doc = factory.newDocumentBuilder().parse(
        "http://stackoverflow.com/feeds/tag?tagnames=java&sort=newest");
    Element root = doc.getDocumentElement();
    XPath xPath = XPathFactory.newInstance().newXPath();
    XPathExpression expression = xPath.compile("http://entry");
    NodeList nl = (NodeList) expression.evaluate(root, XPathConstants.NODESET);
    System.out.println("Found " + nl.getLength() + " items...");
    for (int index = 0; index < nl.getLength(); index++) {
      Node node = nl.item(index);
      expression = xPath.compile("title");
      Node child = (Node) expression.evaluate(node, XPathConstants.NODE);
      System.out.println(child.getTextContent());
    }
  }
}