You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DOM代码获取type元素触发NullPointerException及==与equals差异疑问

DOM操作中获取type元素时触发NullPointerException的问题

我在编写DOM相关代码时遇到了奇怪的问题,代码如下:

public Item getItem(String id) throws ConstructorNotDefinedException {

    //Find the specific item Element we are working with
    Element item = null;

    for (int i = 0; i < this.items.getLength(); i++) { //items is a NodeList of all items, derived from the document Element

        Element currentItem = (Element) this.items.item(i);

        if (currentItem.getAttribute("id") == id) { //only runs once since every ID is unique

            item = currentItem;

        }

    }

    //The line with the error
    Element typeElement = (Element) item.getElementsByTagName("type").item(0);


    //more code using typeElement...
}

主类运行代码如下:

public class test {

    public static void main(String[] args) throws ConstructorNotDefinedException {

        ItemDataReader reader = ItemDataReader.newInstance(Paths.get(System.getProperty("user.home"), "Documents", "path", "to", "xml", "document.xml"));

        Item testItem = reader.getItem("dog");

    }
}

前半部分代码运行完全正常,但当尝试获取typeElement时触发了NullPointerException,我不清楚该异常的来源。

我使用的XML文档示例如下:

<item id="dog">
    <type>1</type>
    <name>Dog</name>
    <strength>10</strength>
</item>
<item id="cat">
    <type>1</type>
    <name>Cat</name>
    <strength>10</strength>
</item>

我尝试了多种方法仍未解决问题,恳请各位提供帮助!


编辑

我采纳了Benjamin W.的建议,使用.equals()方法后问题得以解决,但仍不清楚为何使用==会失效。


问题原因说明

在Java里,==是用来比较对象的内存引用地址,而非字符串的实际内容。currentItem.getAttribute("id")返回的是一个新生成的String对象,和你传入的id参数(比如"dog")虽然内容一致,但属于不同的对象实例,内存地址不相同,所以==判断会返回false,导致item变量始终为null,后续调用item.getElementsByTagName()自然就触发了NullPointerException。

而.equals()方法的作用就是专门比较字符串的内容是否相等,不管两个String对象是不是同一个引用,只要内容匹配就会返回true。所以把判断条件改成currentItem.getAttribute("id").equals(id)就能正确匹配到目标元素,避免item为null的情况。

另外建议增加空值判断,防止getAttribute返回null时调用equals触发新的异常:

if (id != null && id.equals(currentItem.getAttribute("id"))) {
    item = currentItem;
}

内容的提问来源于stack exchange,提问作者Foxler2010

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 17:15:47