App下載
首頁javaxpathJava HTML/XML - 如何使用XPath提取XML表數(shù)據(jù)

Java HTML/XML - 如何使用XPath提取XML表數(shù)據(jù)

我們想知道如何使用XPath提取XML表數(shù)據(jù)。
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.xml.parsers.DocumentBuilder;
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.Node;
import org.w3c.dom.NodeList;

public class Main {
  public static void main(String[] args) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(new File("Table.xml"));

    XPathFactory xFactory = XPathFactory.newInstance();
    XPath path = xFactory.newXPath();
    XPathExpression exp = path.compile("/tables/table");
    NodeList nlTables = (NodeList) exp.evaluate(doc, XPathConstants.NODESET);
    for (int tblIndex = 0; tblIndex < nlTables.getLength(); tblIndex++) {
      Node table = nlTables.item(tblIndex);
      Node nAtt = table.getAttributes().getNamedItem("title");
      System.out.println(nAtt.getTextContent());
      exp = path.compile("headings/heading");
      NodeList nlHeaders = (NodeList) exp.evaluate(table,
          XPathConstants.NODESET);
      Set<String> headers = new HashSet<String>(25);
      for (int index = 0; index < nlHeaders.getLength(); index++) {
        headers.add(nlHeaders.item(index).getTextContent().trim());
      }
      for (String header : headers) {
        System.out.println(header);
      }
      exp = path.compile("tablebody/tablerow");
      NodeList nlRows = (NodeList) exp.evaluate(table, XPathConstants.NODESET);
      for (int index = 0; index < nlRows.getLength(); index++) {
        Node rowNode = nlRows.item(index);
        exp = path.compile("tablecell/item");
        NodeList nlValues = (NodeList) exp.evaluate(rowNode,
            XPathConstants.NODESET);
        List<String> values = new ArrayList<String>(25);
        for (int valueIndex = 0; valueIndex < nlValues.getLength(); valueIndex++) {
          values.add(nlValues.item(valueIndex).getTextContent().trim());
        }
        for (String value : values) {
          System.out.println(value);
        }
       }
     }
  }
}