0

我有这个 xml 文件:

<maths>

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

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

</maths>

我可以使用以下代码成功获取数据:

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

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

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

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

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

谢谢。

4

1 回答 1

1

解析器类:

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

我运行它,它工作正常。希望这可以帮助。

于 2012-11-16T13:49:51.347 回答