首页javajaxbJava HTML/XML - 如何按元素获取属性值

Java HTML/XML - 如何按元素获取属性值

我们想知道如何按元素获取属性值。
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;

public class Main {

  public static void main(String[] args) throws Exception {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document dDoc = builder.parse("input.xml");

    XPath xPath = XPathFactory.newInstance().newXPath();
    String string = (String) xPath.evaluate(
        "/documents/document/element[@name='doctype']/value", dDoc,
        XPathConstants.STRING);
    System.out.println(string);
  }

}