2014-07-27 49 views
0

我正在开发android应用程序。在我的应用程序中,我从服务器获取了xml数据响应,并将其存储在一个字符串中。现在我需要获取该xml的每个值并显示在下拉列表中。我怎样才能做到这一点。请帮我解决一下这个。会非常感激。在android中从xml获取数据

我的XML数据:

<?xml version="1.0" encoding="utf-8"?> 

<root> 
<status>first<status> 
<description>very good</description> 
<Firstnames> 
<name>CoderzHeaven</name> 
<name>Android</name> 
<name>iphone</name> 
</Firstnames> 
<SecondNames> 
<name>Google</name> 
<name>Android</name> 
</SecondNames> 
</root> 

我从服务器获取上述XML数据。现在我需要在列表视图中显示。我如何使用xmlparser获取这些值。我尝试了不同的例子,但它没有为我工作。

回答

0

你需要创建一个额外的类与该类的对象参数化的适配器,例如数据模型将如下所示:

public class DataClass { 

private String status, description; 
private ArrayList<String> fnames, lnames; 

public DataClass() { 
    fnames = new ArrayList<String>(); 
    lnames = new ArrayList<String>(); 
} 

public String getStatus() { 
    return status; 
} 

public void setStatus(String status) { 
    this.status = status; 
} 

public String getDescription() { 
    return description; 
} 

public void setDescription(String description) { 
    this.description = description; 
} 

    public ArrayList<String> getFnames() { 
    return fnames; 
} 

public ArrayList<String> getLnames() { 
    return lnames; 
} 
} 

对于XML解析器,还有数吨的例子,如果你可以使用搜索,你绝对有优势。只是为了给你一个起点,教程one,two,three,four

如果您遇到问题,请发布您的努力和无法使用的代码,您尝试了什么等等。那么你会得到帮助,否则没有人会为你写代码。 https://stackoverflow.com/help/how-to-ask

0

如果xml位于应用程序资产文件夹内,您可以这样做。

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    InputStream input = null; 
    try { 
     input = getApplicationContext().getAssets().open("data.xml"); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    DocumentBuilder builder = null; 
    try { 
     builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); 
    } catch (ParserConfigurationException e) { 
     e.printStackTrace(); 
    } 
    Document doc = null; 
    if (builder == null) { 
     Log.e("TAG", "Builder is empty."); 
     return; 
    } 
    try { 
     doc = builder.parse(input); 
    } catch (SAXException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    if (doc == null) { 
     Log.e("TAG", "Document is empty."); 
     return; 
    } 

    // Get Firstnames element 
    Element firstNames = (Element) doc.getElementsByTagName("Firstnames").item(0); 
    // Get name nodes from Firstnames 
    NodeList nameNodes = firstNames.getElementsByTagName("name"); 
    // Get count of names inside of Firstnames 
    int cChildren = nameNodes.getLength(); 
    List<String> names = new ArrayList<String>(cChildren); 
    for (int i=0; i<cChildren; i++) { 
     names.add(nameNodes.item(i).getTextContent()); 
     Log.d("TAG","Name: "+names.get(i)); 
    } 

    // Do same with SecondNames 
}