我遇到了一些什麼問題應該是簡單的DOM解析。我檢查了很多問題,至今沒有任何事情幫助我的情況。問題是我有一些可能出現在XML中的條件節點,或者可能不會出現。我創建的工具必須將這些值的內容保存到ArrayList中以供以後使用。這裏是有問題的XML:有條件的Java解析 - 獲取子節點內容
-<Dbtr>
-<PstlAdr>
<AdrLine>111 Arlington Ave</AdrLine>
<AdrLine>Apartment A</AdrLine>
<AdrLine>Augusta, AZ 11100</AdrLine>
</PstlAdr>
</Dbtr>
具體來說,Dbtr標記可能出現在XML中的任何次數。對於每個Dbtr標籤,可能會有1-4個AdrLine子女。我需要能夠保存每個AdrLine的值,如果沒有值,則爲每個值保存一個空白的「」值到數組列表中。
要做到這一點,我寫了下面的代碼:
NodeList Dbtr = doc.getElementsByTagName("Dbtr");
for(int i = 0; i < Dbtr.getLength(); i++){
NodeList DbtrChildren = Dbtr.item(i).getChildNodes();
if(DbtrChildren.getLength()==1){
//Add the first child.
}else if(DbtrChildren.getLength()==2){
//Add the first & second child.
}else if(DbtrChildren.getLength()==3){
System.out.println("Test Flag");
System.out.println(DbtrChildren.item(0).getNodeValue()+"Node Value");
System.out.println(DbtrChildren.item(0).getAttributes()+"Text Attributes");
System.out.println(DbtrChildren.item(0).getTextContent()+"Text Content");
}else if(DbtrChildren.getLength()==4){
//Add all 4 children.
}
}
所以根據子女人數AdrLine節點的值,要麼被保存到一個數組列表,或者爲空值將被保存。
問題是,無論我做什麼,我都會爲孩子們獲得空白值。在測試過程中,我可以清楚地看到Dbtr標籤確實有3個孩子。正如你所看到的,我試圖做一些調試來找出獲取值的方法。看到下面的結果:
Test Flag
Node Value
nullText Attributes
Text Content
所以我得到了大量的空白,但沒有價值。當然,我認爲它可能實際上是在拾取「PstlAdr」,但爲什麼它會成功檢測到3個子節點?
任何幫助非常感謝。