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

Jar*_*ves 4 html javascript java 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>
Run Code Online (Sandbox Code Playgroud)

其次,我构建了这个函数,它将文件返回并解析为文档.

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;
}
Run Code Online (Sandbox Code Playgroud)

接下来在我的main方法中,我尝试通过getElementById将Node对象设置为文档elemet,如:

public Document doc = buildDocument("myHTMLFile");
org.w3c.dom.Node node = doc.getElementById("header");//the id of an html element
Run Code Online (Sandbox Code Playgroud)

如果我错了,请纠正我,但这应该导致节点的恢复.但是它返回一个空值.我不明白为什么它没有返回正确的值.注意:在调试代码时,文档确实包含所有正确的数据,据我所知.

use*_*and 11

你做错了.getElementById的 Javadoc javadoc说:

返回具有给定值的ID属性的Element.如果不存在此类元素,则返回null.... DOM实现应该使用属性Attr.isId来确定属性是否为ID类型. 注意:除非如此定义,否则名称为"ID"或"id"的属性不是ID类型.

在您的情况下,最好的解决方案是使用XPath(XML的简单查询语言):

XPath xpath = XPathFactory.newInstance().newXPath();
Node node = (Node) xpath.evaluate("//*[@id='header']", document, XPathConstants.NODE);
Run Code Online (Sandbox Code Playgroud)

表达式//*[@ id ='header'] - 选择文档中具有'header'值属性id的所有节点.