在android中解析一个xml文件 [英] Parsing an xml file in android

查看:26
本文介绍了在android中解析一个xml文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 xml 文件:

I have this xml file:

<maths>

<mathametician>
<id>101</id>
<name>kurt</name>
<age>75</age>
</mathametician>

<mathametician>
<id>102</id>
<name>david</name>
<age>62</age>
</mathametician>

</maths>

并且我可以使用此代码成功获取数据:

And I can successfully get data using this code:

        try {
            InputStream raw = this.getApplicationContext().getAssets()
                    .open("maths.xml");

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();

            Document doc = db.parse(raw);
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getElementsByTagName("mathametician");

            for (int i = 0; i < nodeList.getLength(); i++) {

                Node node = nodeList.item(i);
                Element fstElmnt = (Element) node;

                NodeList websiteList = fstElmnt.getElementsByTagName("age");
                Element websiteElement = (Element) websiteList.item(0);
                websiteList = websiteElement.getChildNodes();

                Toast.makeText(getApplicationContext(),
                        websiteList.item(0).getNodeValue(), Toast.LENGTH_SHORT)
                        .show();
            }

我的问题是:为什么我不能直接获取数据:

My question is: why can't I get data directly after:

NodeList websiteList = fstElmnt.getElementsByTagName("age");

除非我写,否则我会得到空结果:

I get empty results unless I write:

Element websiteElement = (Element) websiteList.item(0);
websiteList = websiteElement.getChildNodes();

谢谢.

推荐答案

解析器类:

public final class SampleParser{


    final static String ROOT_NODE = "maths";
    final static String ELEMENT_MATHAMETICIAN = "mathametician";
    final static String ELEMENT_ID = "id";
    final static String ELEMENT_NAME = "name";
    final static String ELEMENT_AGE = "age";

    private static final String TAG="SampleParser";

    /**
     * Intentionally commented
     */
    private SampleParser() {}

    /**
     * @param response The XML string which represents the complete news data
     * @return news The complete data
     */
    public static Maths parse(String response) {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp;
        try {
            sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();
            SampleDataHandler dataHandler = new SampleDataHandler();
            xr.setContentHandler(dataHandler);
            InputSource source = new InputSource(new StringReader(response)); 
            xr.parse(source);
            Maths result = dataHandler.getData();
            return result;
        } catch (ParserConfigurationException e) {
            Log.e(TAG, "parse", e);
        } catch (SAXException e) {
            Log.e(TAG, "parse", e);
        } catch (IOException e) {
            Log.e(TAG, "parse", e);
        } 
        return null;
    }

    static class SampleDataHandler extends DefaultHandler {
        /**
         * 
         */
        private static final String TAG="NewsDataHandler";
        /**
         * 
         */
        private Maths data;
        /**
         * 
         */
        private Mathematician tempElement;
        /**
         * 
         */
        private boolean readingAge;
        /**
         * 
         */
        private boolean readingName;
        /**
         * 
         */
        private boolean readingID;
        /**
         * 
         */
        public Maths getData(){
            return data;
        }

        /*
         * (non-Javadoc)
         * 
         * @see org.xml.sax.helpers.DefaultHandler#endDocument()
         */
        @Override
        public void endDocument() throws SAXException {
            Log.d(TAG, "endDocument Finished parsing response");
        }

        /*
         * (non-Javadoc)
         * 
         * @see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String,
         * java.lang.String, java.lang.String)
         */
        @Override
        public void endElement(String uri, String localName, String qName)
                throws SAXException {
            if(qName.equalsIgnoreCase(ELEMENT_MATHAMETICIAN)){
                data.addMathematician(tempElement);
            }else if(qName.equalsIgnoreCase(ELEMENT_ID)){
                readingID = false;
            }else if(qName.equalsIgnoreCase(ELEMENT_NAME)){
                readingName = false;
            }else if(qName.equalsIgnoreCase(ELEMENT_AGE)){
                readingAge = false;
            }
        }

        /*
         * (non-Javadoc)
         * 
         * @see org.xml.sax.helpers.DefaultHandler#startDocument()
         */
        @Override
        public void startDocument() throws SAXException {
            data = new Maths();
            Log.d(TAG, "startDocument Started parsing response");
        }

        /*
         * (non-Javadoc)
         * 
         * @see
         * org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String,
         * java.lang.String, java.lang.String, org.xml.sax.Attributes)
         */
        @Override
        public void startElement(String uri, String localName, String qName,
                Attributes attributes) throws SAXException {
            if(qName.equalsIgnoreCase(ROOT_NODE)){
                //data.setData(new ArrayList<NewsElement>());
            }else if(qName.equalsIgnoreCase(ELEMENT_AGE)){
                readingAge=true;                
            }else if(qName.equalsIgnoreCase(ELEMENT_MATHAMETICIAN)){
                tempElement = new Mathematician();
            }else if(qName.equalsIgnoreCase(ELEMENT_ID)){
                readingID=true;
            }else if(qName.equalsIgnoreCase(ELEMENT_NAME)){
                readingName=true;
            }
        }

        /*
         * (non-Javadoc)
         * 
         * @see org.xml.sax.helpers.DefaultHandler#characters(char[], int, int)
         */
        @Override
        public void characters(char[] ch, int start, int length)
                throws SAXException {
            String chars = new String(ch, start, length);    
            chars = chars.trim(); 
            if(readingID){
                try{
                    tempElement.setId(Integer.parseInt(chars));
                }catch(Exception e){
                    Log.e(TAG, "characters[Parsing ID]", e);
                    tempElement.setId(-1);
                }
            }
            else if(readingAge){
                try{
                    tempElement.setAge(Integer.parseInt(chars));
                }catch(Exception e){
                    Log.e(TAG, "characters[Parsing Age]", e);
                    tempElement.setAge(-1);
                }
            }else if(readingName){
                tempElement.setName(chars);
            }
        }
    }
}

使用的 POJO:

public class Maths {

    private ArrayList<Mathematician> mathematicians;

    /**
     * @return the mathematicians
     */
    public ArrayList<Mathematician> getMathematicians() {
        return mathematicians;
    }

    /**
     * @param mathematicians the mathematicians to set
     */
    public void setMathematicians(ArrayList<Mathematician> mathematicians) {
        this.mathematicians = mathematicians;
    }

    /**
     * @param item The item to add
     */
    public void addMathematician(Mathematician item){
        if(null == mathematicians){
            mathematicians = new ArrayList<Mathematician>();
        }
        mathematicians.add(item);
    }
}

<小时>

public class Mathematician {

    private int id;
    private String name;
    private int age;
    /**
     * @return the id
     */
    public int getId() {
        return id;
    }
    /**
     * @param id the id to set
     */
    public void setId(int id) {
        this.id = id;
    }
    /**
     * @return the name
     */
    public String getName() {
        return name;
    }
    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }
    /**
     * @return the age
     */
    public int getAge() {
        return age;
    }
    /**
     * @param age the age to set
     */
    public void setAge(int age) {
        this.age = age;
    }
}

我运行了它,它运行良好.希望这会有所帮助.

I ran it and it works fine. Hope this helps.

这篇关于在android中解析一个xml文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆