首页javaxpathJava HTML/XML - 如何从XPath查询获取节点列表

Java HTML/XML - 如何从XPath查询获取节点列表

我们想知道如何从XPath查询获取节点列表。
import java.io.FileReader;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class Main {

  public static void main(String[] args) throws Exception {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xPath = factory.newXPath();

    NodeList shows = (NodeList) xPath.evaluate("/schedule/show", new InputSource(new FileReader(
        "tds.xml")), XPathConstants.NODESET);
    for (int i = 0; i < shows.getLength(); i++) {
      Element show = (Element) shows.item(i);
      String guestName = xPath.evaluate("guest/name", show);
      System.out.println(guestName);
      System.out.println(show.getAttribute("weekday") + ", " + show.getAttribute("date"));
    }

  }

}