我正在尝试从一个文件中获取一个 html 节点,该文件稍后将用于计算其所有后代。我在从 DOM 中检索元素时遇到问题。以下是我到目前为止采取的步骤。
首先是我的html代码:
<html>
<head>
<title></title>
</head>
<body>
<div id="container">
<a></a>
<div id="header">
<div id="firstchild">
<div>
<img></img>
</div>
<a></a>
<ul>
<li>
<a>Inbox</a>
</li>
<li>
<a>Logout</a>
</li>
</ul>
<form></form>
</div>
<div id="nextsibling"></div>
</div>
</div>
</body>
</html>
其次,我构建了这个函数,它将返回文件并将其解析为文档。
public static Document buildDocument(String file){
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document document = docBuilder.parse(file);
return document;
} catch (ParserConfigurationException | SAXException | IOException ex) {
System.out.println("the exception is: " + ex.toString());
}
return null;
}
接下来,在我的主要方法中,我尝试通过 getElementById 将 Node 对象设置为文档元素,例如:
public Document doc = buildDocument("myHTMLFile");
org.w3c.dom.Node node = doc.getElementById("header");//the id of an html element
如果我错了,请纠正我,但这应该会导致节点的检索。但是它返回一个空值。我不明白为什么它没有返回正确的值。注意:据我所知,在调试代码时,文档确实包含所有正确的数据。
最佳答案
你做错了。 Java文档 javadoc of getElementById说:
Returns the Element that has an ID attribute with the given value. If no such element exists, this returns null . ... The DOM implementation is expected to use the attribute Attr.isId to determine if an attribute is of type ID. Note: Attributes with the name "ID" or "id" are not of type ID unless so defined.
在您的情况下,最好的解决方案是使用 XPath (XML 的简单查询语言):
XPath xpath = XPathFactory.newInstance().newXPath();
Node node = (Node) xpath.evaluate("//*[@id='header']", document, XPathConstants.NODE);
表达式 //*[@id='header'] - 选择文档中具有属性 id 和 'header' 值的所有节点。
关于java - 无法使用 document.getElementById 获取元素,返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21357451/