如何从资产中解析XML,保留它并添加到ListVIew?

时间:2015-02-07 07:17:11

标签: android xml listview

我被告知解析XML文件。任务是从assets文件夹解析XML,并以某种方式将其放入ListView。此外,xml包含链接,当你点击特定的ListView项时,你应该从相应的链接获取文件(你应该得到解析的CSV文件,其中包含链接。而这个解析的CSV必须存储在本地数据库中,但那是另一个故事)

这是我的XML:

<Table>
    <TableItem>
        <id>1</id>
        <title>bla-bla-bla</title>
        <url>http://thelink</url>
        <type>CSV</type>
    </TableItem>
    <TableItem>
        <id>2</id>
        <title>bla-bla-bla x2</title>
        <url>thelink</url>
        <type>CSV</type>
    </TableItem>
    <TableItem>
        <id>3</id>
        <title>bla-bla-bla</title>
        <url>the link</url>
        <type>CSV</type>
    </TableItem>

    .....
    </Table>

如何解析此类XML?我已经尝试过XMLparser了,它对我不起作用。现在我尝试使用SAXParser,我需要正确地描述Handler。

public void parseThat() throws IOException, ParserConfigurationException, SAXException {
    InputSource inputSource = new InputSource(this.getActivity().getAssets().open("Table.xml"));
    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    SAXParser saxParser = saxParserFactory.newSAXParser();
    XMLReader xmlReader = saxParser.getXMLReader();
    xmlReader.parse(inputSource);
}

这是Handler:

public class XmlContentHandler extends DefaultHandler
{
    List<TableItem> items = new ArrayList<TableItem>();
    private boolean inTableItem = false;
    private boolean inTitle = false;
    private boolean inUrl = false;
    private boolean inType = false;

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        super.startElement(uri, localName, qName, attributes);
        if(localName.equals("TableItem"))
        {

        }
    }

    class TableItem{
        String title;
        String type;
        String url;

        private TableItem(String title, String type, String url)
        {
            this.title = title;
            this.url = url;
            this.type = type;
        }
    }
}

非常感谢任何帮助和想法!

0 个答案:

没有答案