2013-07-02 219 views
0

我的XML文件是这样的 - >如何从.xml文件读取信息

<Lang> 

    <Setting> 

    <DisplayIndex>6</DisplayIndex> 

    <Visible>True</Visible> 

    <Width>289</Width> 

    </Setting> 

    <Variable ID="1" Name="a">word1</Variable> 

    <Variable ID="2" Name="b">word2</Variable> 

    <Variable ID="3" Name="c">word3</Variable> 

    ... 

    </Lang> 

我想从它那里得到ID(或名称)和值。

1.我可以放置我的.xml文件吗?

2.如何从.xml文件中获取ID(或名称)和值?

回答

0
  1. 认沽读取文件您的XML在资产文件夹中。
  2. 我建议使用JDOM XML解析器 - http://www.jdom.org/ 这将是这样的:

    Document document = (Document) builder.build(xmlFile); 
    Element rootNode = document.getRootElement(); 
    List list = rootNode.getChildren("Variable"); 
    for (int i = 0; i < list.size(); i++) { 
        Element node = (Element) list.get(i); 
        String id = node.getAttributeValue("ID"); 
        String value = node.getText(); 
    }  
    
0

请按照this教程解析XML数据。该教程从设备的SD卡内的文件中读取数据。您可以将您的XML文件放置在项目的sdcardraw文件夹中。

如果XML文件是在项目的原始文件夹,那么你必须得到InputSource这样

InputSource is = new InputSource(getResources().openRawResource(R.raw.yourxmlfile)); 

和文件应该从byteStream

Document doc=db.parse(new InputSource(is.getByteStream()));