<?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的長(zhǎng)度為7?
1 回答

POPMUISE
TA貢獻(xiàn)1765條經(jīng)驗(yàn) 獲得超5個(gè)贊
那是因?yàn)閎ookElement.getChildNodes()方法,會(huì)將bookElement下的文本節(jié)點(diǎn)也當(dāng)作一個(gè)子節(jié)點(diǎn),就像這樣:
#text
<name>
#text
<price>
#text
<author>
#text
其中#text這個(gè)文本節(jié)點(diǎn),你是肉眼看不到的,它也許是一個(gè)空格或者換行符。
如果題主不希望得到需要的節(jié)點(diǎn),建議在操作節(jié)點(diǎn)之前,判斷一下節(jié)點(diǎn)的類型是不是Node.TEXT_NODE。
添加回答
舉報(bào)
0/150
提交
取消