2011年8月30日 星期二

[Android] How to read and parse xml files in android application.

I have a xml file named books.xml that is stored in my pad.

<?xml version="1.0" encoding="UTF-8"?>
<library-metadata title="My library">
  <book-metadata name="One Day" author="Nicholls, David">
    <publish-info publisher="Random House Inc" date="05-24-2011" ISBN="9780307946713"/>
  </book-metadata>
  <book-metadata name="Transformers: Exodus" author="Irvine, Alex">
    <publish-info publisher="Random House" date="06-28-2011" ISBN="9780345522528"/>
  </book-metadata>
</book-metadata>

I want to read the xml content and save it to my custom class.
The code as below.


        final String path = Environment.getExternalStorageDirectory().getPath() + "/books.xml";
        FileInputStream fstream = null;
        try
        {
            // read file.
            fstream = new FileInputStream(path);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(fstream);
            Element root = document.getDocumentElement();


            NodeList bookList = root.getElementsByTagName("book-metadata");
            for (int i = 0; i < bookList.getLength(); i++)
            {
                Element bookElement = (Element) bookList.item(i);


                NodeList publishList = bookElement.getElementsByTagName("publish-info");
                for (int j = 0; j < publishList.getLength(); j++)
                {
                    classBooks myBook = new classBooks();
                    Element publishElement = (Element) publishList.item(j);


                    // get xml value and set it into class object.
                    myBook.setName(Integer.parseInt(bookElement.getAttribute("name")));
                    myBook.setAuthor(bookElement.getAttribute("author"));
                    myBook.setPublisher(publishElement.getAttribute("publisher"));
                    myBook.setPublishDate(publishElement.getAttribute("date"));
                    myBook.setISBN(publishElement.getAttribute("ISBN"));


                    m_bookList.add(myBook);  // m_bookList is a member collection variable.
                }
            }
        }
        catch (Exception exception)
        {
            exception.printStackTrace();
        }
        finally
        {
            if (null != fstream)
            {
                fstream.close();
            }
        }

沒有留言:

張貼留言