Search code examples
javaandroidxmlsax

How to save data when parsing XML?


I have a xml-file:

<?xml version="1.0" encoding="utf-8" ?>
<list>
<file name="a" size="559393"/>
<file name="b" size="1766945"/>
...
</list>

With SAX-parser I need to get the attribute values (in my case the name and size values of all tags file) and write in a collection for the further work my program.

How should I realize this? For each tag file to create an object with the fields name and size, and add it all to the ArrayListObject?


Solution

  • yes , you should have already object with name and size attributes , and while you in start element method , do something like this .

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes)
            throws SAXException {
    
        if (qName.equalsIgnoreCase("file")) {
            String name = attributes.getValue("name");
            String size = attributes.getValue("size");
            file file = new file (name,size);
            list.add(file);
            }
          }