在DefaultHandler类中获取XML标记的值

时间:2014-07-08 19:53:21

标签: java android xml

我使用DefaultHandler来解析我的项目来解析XML。

假设我们有以下XML:

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

startElement(String uri, String localName, String qName, Attributes attributes)方法中,我们可以在name对象中获取vicinity localName等父标记的名称及其在{{1}中的归属值像attributes这样的对象。

但是,如果我想获得标签之间的价值而不是其归因于例如对于attributes.getValue("id"),没有归因于其内部的值,所以我如何在此处检索它?

三江源!

2 个答案:

答案 0 :(得分:0)

您应该使用XMLPullParser(http://developer.android.com/reference/org/xmlpull/v1/XmlPullParser.html),因为它对Android来说更容易,更有效。

但对于SAX,这里有一个关于如何解析的例子。

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>

有一个模型类在我们解析数据之后存储数据,但忽略这一点只是你需要知道的解析。

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;
}
}

答案 1 :(得分:0)

关于解析XML数据的Android官方培训网站上有一个很好的教训。他们的演示数据比你的更复杂:

<?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>

您可以使用parser.getAttributeValue()parser.getText()来获取您的价值。您应该查看training course上的更多详细信息。希望这会对您有所帮助。