首页javaxpathJava HTML/XML - 如何使用XPath解析XML文件的属性值

Java HTML/XML - 如何使用XPath解析XML文件的属性值

我们想知道如何使用XPath解析XML文件的属性值。
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;

public class Main {

  private static final String CFG_FILE = "test.xml";
  private static final String XPATH_FOR_PRM_MaxThread = "/config/param[@id='MaxThread']/text()";

  public static void main(String[] args) throws Exception {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setNamespaceAware(true);
    DocumentBuilder builder;
    builder = docFactory.newDocumentBuilder();
    Document doc = builder.parse(CFG_FILE);
    XPathExpression expr = XPathFactory.newInstance().newXPath()
        .compile(XPATH_FOR_PRM_MaxThread);
    Object result = expr.evaluate(doc, XPathConstants.NUMBER);
    if (result instanceof Double) {
      System.out.println(((Double) result).intValue());
    }

  }
}