0

I am using DefaultHandler for on of my projects to parse XML.

Let's say we have following XML:

<name id="11">something</name>
<vicinity>vicinity value</vicinity>
<type>establishment</type>

Inside the startElement(String uri, String localName, String qName, Attributes attributes) method we can get the names of parent tags like name vicinity etc. in localName object and the value of its attributed in attributes object like attributes.getValue("id").

But what if I want to get the value in between tags not its attributed for e.g. for vicinity there are not attributed buts its value inside it, so how I can retrieve it here?

2 Answers 2

0

You should be using XMLPullParser (http://developer.android.com/reference/org/xmlpull/v1/XmlPullParser.html) becuase it is easier and more efficient for Android.

But for SAX here is an example on how to parse.

XML:

<users>
<user id="100">
    <firstname>Tom</firstname>
    <lastname>Hanks</lastname>
</user>
<user id="101">
    <firstname>Lokesh</firstname>
    <lastname>Gupta</lastname>
</user>
<user id="102">
    <firstname>HowToDo</firstname>
    <lastname>InJava</lastname>
</user>

There is a model class that stores the data after we parse it, but ignoring that here is just what you need to know for the parsing.

import java.util.ArrayList;
import java.util.Stack;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class UserParserHandler extends DefaultHandler
{
//This is the list which shall be populated while parsing the XML.
private ArrayList userList = new ArrayList();

//As we read any XML element we will push that in this stack
private Stack elementStack = new Stack();

//As we complete one user block in XML, we will push the User instance in userList
private Stack objectStack = new Stack();

public void startDocument() throws SAXException
{
    //System.out.println("start of the document   : ");
}

public void endDocument() throws SAXException
{
    //System.out.println("end of the document document     : ");
}

public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
{
    //Push it in element stack
    this.elementStack.push(qName);

    //If this is start of 'user' element then prepare a new User instance and push it in object stack
    if ("user".equals(qName))
    {
        //New User instance
        User user = new User();

        //Set all required attributes in any XML element here itself
        if(attributes != null &amp;&amp; attributes.getLength() == 1)
        {
            user.setId(Integer.parseInt(attributes.getValue(0)));
        }
        this.objectStack.push(user);
    }
}

public void endElement(String uri, String localName, String qName) throws SAXException
{
    //Remove last added  element
    this.elementStack.pop();

    //User instance has been constructed so pop it from object stack and push in userList
    if ("user".equals(qName))
    {
        User object = this.objectStack.pop();
        this.userList.add(object);
    }
}

/**
 * This will be called everytime parser encounter a value node
 * */
public void characters(char[] ch, int start, int length) throws SAXException
{
    String value = new String(ch, start, length).trim();

    if (value.length() == 0)
    {
        return; // ignore white space
    }

    //handle the value based on to which element it belongs
    if ("firstName".equals(currentElement()))
    {
        User user = (User) this.objectStack.peek();
        user.setFirstName(value);
    }
    else if ("lastName".equals(currentElement()))
    {
        User user = (User) this.objectStack.peek();
        user.setLastName(value);
    }
}

/**
 * Utility method for getting the current element in processing
 * */
private String currentElement()
{
    return this.elementStack.peek();
}

//Accessor for userList object
public ArrayList getUsers()
{
    return userList;
}
}
0

There is a good lesson on the android official training site about Parsing XML Data.And their demo data is more complicate than yours:

<?xml version="1.0" encoding="utf-8"?> 
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" ...">     
<title type="text">newest questions tagged android - Stack Overflow</title>
...
    <entry>
    ...
    </entry>
    <entry>
        <id>http://stackoverflow.com/q/9439999</id>
        <re:rank scheme="http://stackoverflow.com">0</re:rank>
        <title type="text">Where is my data file?</title>
        <category scheme="http://stackoverflow.com/feeds/tag?tagnames=android&sort=newest/tags" term="android"/>
        <category scheme="http://stackoverflow.com/feeds/tag?tagnames=android&sort=newest/tags" term="file"/>
        <author>
            <name>cliff2310</name>
            <uri>http://stackoverflow.com/users/1128925</uri>
        </author>
        <link rel="alternate" href="http://stackoverflow.com/questions/9439999/where-is-my-data-file" />
        <published>2012-02-25T00:30:54Z</published>
        <updated>2012-02-25T00:30:54Z</updated>
        <summary type="html">
            <p>I have an Application that requires a data file...</p>
        </summary>
    </entry>
    <entry>
    ...
    </entry>
...
</feed>

You can use parser.getAttributeValue() or parser.getText() to get your value.You should check more detail on the training course.Wish this would help you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.