2012-07-29 266 views
0

我有以下XML,XML解析:無法解析XML正確

<toplevel> 
<CompleteSuggestion> 
<suggestion data="rahm emanuel"/> 
<num_queries int="6350000"/> 
</CompleteSuggestion> 
<CompleteSuggestion> 
<suggestion data="raheem devaughn"/> 
<num_queries int="2130000"/> 
</CompleteSuggestion> 
<CompleteSuggestion> 
<suggestion data="rahat fateh ali khan"/> 
<num_queries int="9020000"/> 
</CompleteSuggestion> 
<CompleteSuggestion> 
<suggestion data="rahab"/> 
<num_queries int="1690000"/> 
</CompleteSuggestion> 
<CompleteSuggestion> 
<suggestion data="rahr brewery"/> 
<num_queries int="113000"/> 
</CompleteSuggestion> 
<CompleteSuggestion> 
<suggestion data="rahsaan patterson"/> 
<num_queries int="472000"/> 
</CompleteSuggestion> 
<CompleteSuggestion> 
<suggestion data="rahul gandhi"/> 
<num_queries int="14600000"/> 
</CompleteSuggestion> 
<CompleteSuggestion> 
<suggestion data="rah digga"/> 
<num_queries int="1180000"/> 
</CompleteSuggestion> 
<CompleteSuggestion> 
<suggestion data="rahxephon"/> 
<num_queries int="1660000"/> 
</CompleteSuggestion> 
<CompleteSuggestion> 
<suggestion data="rahway nj"/> 
<num_queries int="3690000"/> 
</CompleteSuggestion> 
</toplevel> 

這是從谷歌API的輸出。我想解析我的Android應用程序。我正在使用DOM來解析它。我有以下代碼。

Document doc = null; 
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
    try { 

     DocumentBuilder db = dbf.newDocumentBuilder(); 

     InputSource is = new InputSource(); 
     is.setCharacterStream(new StringReader(xml)); 
     doc = db.parse(is); 

    } 

    Element root = doc.getDocumentElement(); 

    NodeList nl = doc.getElementsByTagName("CompleteSuggestion"); 

    for (int i = 0; i < nl.getLength(); i++) { 
     Element suggestion = (Element)nl.item(i); 
     String name = suggestion.getAttribute("suggestion"); 
     System.out.println(name); 
    } 

我無法獲得正確的屬性值。它每次都是空的。

Thx! rahul。

+0

String name = suggestion.getAttribute(「data」);猜測 – 2012-07-29 13:15:39

回答

0

建議不是屬性其元素,數據是元素建議的屬性。 使用這個:

for (int i = 0; i < nl.getLength(); i++) { 
     Element c_suggestion = (Element)nl.item(i); 
     Element suggestion = c_suggestion.getElementsByTagName("Suggestion") 
     String name = suggestion.getAttribute("data"); 
     System.out.println(name); 
    }