我有以下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>
这是google 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! 拉胡
答案 0 :(得分: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);
}