0

我有以下 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);
    }

我无法获得正确的属性值。每次都是空的。

谢谢!拉胡尔

4

1 回答 1

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);
    }
于 2012-07-30T11:55:03.277 回答