<?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 回答

POPMUISE
TA贡献1765条经验 获得超5个赞
那是因为bookElement.getChildNodes()方法,会将bookElement下的文本节点也当作一个子节点,就像这样:
#text
<name>
#text
<price>
#text
<author>
#text
其中#text这个文本节点,你是肉眼看不到的,它也许是一个空格或者换行符。
如果题主不希望得到需要的节点,建议在操作节点之前,判断一下节点的类型是不是Node.TEXT_NODE。
添加回答
举报
0/150
提交
取消