首页javaxpathJava HTML/XML - 如何获取特定XML标记的值

Java HTML/XML - 如何获取特定XML标记的值

我们想知道如何获取特定XML标记的值。
import java.io.StringReader;

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

import org.xml.sax.InputSource;

public class Main {

  private static final String XML = "<dennis><hair>brown</hair><pants>blue</pants><gender>male</gender></dennis>";

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

    InputSource inputSource = new InputSource(new StringReader(XML));
    String result = (String) xPath.evaluate("//gender", inputSource,
        XPathConstants.STRING);
    System.out.println(result);
  }

}