java解析xml getChilidNotes的length怎么看?
迷茫
迷茫 2017-04-17 16:27:55
[Java讨论组]
<?xml version="1.0" encoding="UTF-8"?>
<books>
    <book id="12">
        <name>think in java</name>
        <price>85.5</price>
        <author>Edwrad Saverin</author>
    </book>
    <book id="15">
        <name>Spring in Action</name>
        <price>39.0</price>
        <author>Edward Saverin</author>    
    </book>
</books>
NodeList bookNodes=element.getElementsByTagName("book");
        for(int i=0;i<bookNodes.getLength();i++){
            Element bookElement=(Element)bookNodes.item(i);
            Book book=new Book();
            book.setId(Integer.parseInt(bookElement.getAttribute("id")));
            NodeList childNodes=bookElement.getChildNodes();
            System.out.println("childnodes:"+childNodes.getLength());

为什么childnodes的长度为7?

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

全部回复(1)
黄舟

那是因为bookElement.getChildNodes()方法,会将bookElement下的文本节点也当作一个子节点,就像这样:

#text
<name>
#text
<price>
#text
<author>
#text

其中#text这个文本节点,你是肉眼看不到的,它也许是一个空格或者换行符。
如果题主不希望得到需要的节点,建议在操作节点之前,判断一下节点的类型是不是Node.TEXT_NODE

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号