Posted on 2006-11-24 12:41
兵臨城下 閱讀(425)
評論(5) 編輯 收藏 所屬分類:
J2SE
有這樣一段代碼:
???????public static Node findNode(Node node, String name)
?{
?????????NodeList list = node.getChildNodes();
?????????int size = list.getLength();
?????????for (int i = 0; i < size; i++)
?????????{
?????????????Node node = list.item(i);
?????????????if(node.getNodeType()!=Node.ELEMENT_NODE)?
???????????????????continue;?
?????????????if (node.getNodeName().equals(name))
??????????????????return node;??
????????}
?}
注意其中標(biāo)紅的這句代碼,為什么要加這個判斷?我在調(diào)試過程中發(fā)現(xiàn)這段代碼確實有用,但為什么有時一樣的node結(jié)構(gòu),為什么有時能檢測到非ELEMENT_NODE type 的節(jié)點,有時卻是直接跳過呢?
??????詢問一些同事說,在xml結(jié)構(gòu)中如果存在非法的空格,xml解析器也會把它解析成一個node,但nodetype不是element而已,是這樣嗎,是不是還有其他的原因?
評論
from dom4j api doc:
public short getNodeType()Returns the code according to the type of node. This makes processing nodes polymorphically much easier as the switch statement can be used instead of multiple if (instanceof) statements.
Returns:
a W3C DOM complient code for the node type such as ELEMENT_NODE or ATTRIBUTE_NODE
不要把xml完全數(shù)據(jù)格式,也可當(dāng)成文本。比如<p>text<b>book</b>name</p>,當(dāng)node取p時,那個代碼就有用了。
有可能返回一個Element節(jié)點或者屬性節(jié)點吧
<p>text<b>book</b>name</p>
這種格式是標(biāo)準(zhǔn)的xml格式嗎?如果這樣,在xml解析時能通過?
不知道什么樣的節(jié)點才是Element或是屬性節(jié)點呢?Elment也是繼承自Node的