在android中使用SAXParser解析xml

时间:2013-11-25 05:35:50

标签: android saxparser

这里我要使用SAX Parser解析xml文件,我完全解析了它。下面是我的xml文件。

category.xml

<main>

        <category>
            <id>1</id>
            <item>hey whats up?</item>
         </category>       

        <category>
            <id>2</id>
            <item>Hello !!</item>
        </category>

        <category>
            <id>3</id>
            <item>Good Morning.</item>
        </category>

</main>

但是现在我想基于id解析其他xml文件。当用户点击“嘿哇哇哇哇哇哇哇哇哇哇”如果id = 1,则应显示其他xml文件中id = 1的数据(此处数据为“One”和“Two”)。

second.xml

<main>

        <category>
            <id>1</id>
            <item>one</item>
            <item>two</item>
         </category>       

        <category>
            <id>2</id>
            <item>three</item>
            <item>four</item>
        </category>


</main>

以下是我的.java类。

SAXXMLHandler.java

public class SAXXMLHandler extends DefaultHandler {

    private List<Employee> employees;
    private String tempVal;
    private Employee tempEmp;

    public SAXXMLHandler() {
        employees = new ArrayList<Employee>();
    }

    public List<Employee> getEmployees() {
        return employees;
    }

    // Event Handlers
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException 
    {
        // reset
        tempVal = "";
        if (qName.equalsIgnoreCase("category")) 
        {
            // create a new instance of employee
            tempEmp = new Employee();
        }
    }

    public void characters(char[] ch, int start, int length) throws SAXException 
    {
        tempVal = new String(ch, start, length);
    }

    public void endElement(String uri, String localName, String qName) throws SAXException 
    {
        if (qName.equalsIgnoreCase("category")) 
        {
            // add it to the list
            employees.add(tempEmp);
        }


        else if (qName.equalsIgnoreCase("item")) 
        {
            tempEmp.setItem(tempVal);
        }  

        else if (qName.equalsIgnoreCase("id")) 
        {
            tempEmp.setId(Integer.parseInt(tempVal));
        }  

    }
}

Employee.java

public class Employee {

    private String item;
    private int id;

    public String getItem() {
        return item;
    }

    public void setItem(String item) {
        this.item = item;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return item + ": " + id;
    }

    public String getDetails() {
        String result = "Id" + ": " + id + "\n"  ;
        return result;
    }

}

SAXParserActivity.java

public class SAXParserActivity extends Activity {

    Button button, btnAdd;
    ListView lv;
    List<Employee> employees = null;
    EditText et;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        lv = (ListView) findViewById(R.id.spinner);

        try
        {
            employees = SAXXMLParser.parse(getAssets().open("XML/category.xml"));
            ArrayAdapter<Employee> adapter = new ArrayAdapter<Employee>(this, R.layout.list_item, employees);
            lv.setAdapter(adapter);

        } catch (IOException e) {
            e.printStackTrace();
        }

        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View arg1, int pos,
                    long arg3) {
                Employee employee = (Employee) parent.getItemAtPosition(pos);
                Toast.makeText(parent.getContext(), employee.getDetails(),
                        Toast.LENGTH_LONG).show();

            }
        });


    }



}

如何根据用户选择解析第二个xml文件?

1 个答案:

答案 0 :(得分:1)

您可以使用Xpath。实现起来非常简单。以下是代码。

yourxml.xml

<main>
       <category id="Love">
                <item>Love u</item>
                <item>Love u too</item>

        </category>

          <category id="Birthday">
                <item>Happy Bday</item>
                <item>Many Many Happy</item>
                <item>Have a blast</item>
        </category>
</main>

的.java

import java.util.ArrayList;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Toast;

public class XPathStudyActivity extends ListActivity {
    // data
    ArrayList<String> mPeople = new ArrayList<String>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        try {
            parseData();
        } catch(Exception ex) {
            Toast.makeText(this, "Exception: " + ex.getMessage(), Toast.LENGTH_LONG).show();
        }

        // pass adapter w/ data queried through XPath to ListView
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mPeople);
        setListAdapter(adapter);
    }

    private void parseData() throws Exception {
        // create an InputSource object from /res/raw
        InputSource inputSrc = new InputSource(getResources().openRawResource(R.raw.data));
        // query XPath instance, this is the parser
        XPath xpath = XPathFactory.newInstance().newXPath();
        // specify the xpath expression
        String expression = "//main";
        // list of nodes queried
        NodeList nodes = (NodeList)xpath.evaluate(expression, inputSrc, XPathConstants.NODESET);

        Toast.makeText(this, "count: " + String.valueOf(nodes.getLength()),Toast.LENGTH_SHORT).show();
        // if node found
        if(nodes != null && nodes.getLength() > 0) {
            mPeople.clear();
            int len = nodes.getLength();
            for(int i = 0; i < len; ++i) {
                // query value
                Node node = nodes.item(i);
                mPeople.add(node.getTextContent());
            }
        }
    }
}

您也可以从此链接获得参考

Link