java - 无法使用 document.getElementById 获取元素,返回 null

标签 java javascript html parsing dom

我正在尝试从一个文件中获取一个 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/

相关文章:

java.lang.NullPointerException - 找不到 null 变量

javascript - 如何通过 api 获取数据并用它渲染子组件 - react 谷歌地图

javascript - 在选择下拉列表的值时显示复选框列表

javascript - 这些额外参数如何与 map() 一起使用?

javascript - 如何通过单击导航按钮开始/结束 smoke.js 动画?

java - com.microsoft.sqlserver.jdbc.SQLServerException : The value is not set for the parameter number 1

java - 从 process.getErrorStream() 读取时 BufferedReader 阻塞

jquery - 将两个表合并为单个表JQuery

java - 通过类加载器加载的 java 类的成员未初始化

javascript - 获取 jquery 元素值