XML Parser返回最后一项,而不是其余项

时间:2013-11-27 04:43:57

标签: android android-xml

我的XML内容:(FileName:sku.xml)

<skus>
<id>p1</id>
<id>test</id>
<id>aa</id>
<id>bb</id>
<id>cc</id>
<id>dd</id>
<id>ee</id>
<id>ff</id>
<id>gg</id>
<id>hh</id>
<id>ii</id>
<id>jj</id>
<id>kk</id>
<id>ll</id>
</skus>

我的SAX XML PARSER类:

公共类SAXXMLParser {

public static List<XMLSetAdd> parse(InputStream is) {
    List<XMLSetAdd> setAdds = null;
    try {
        // create a XMLReader from SAXParser
        XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser()
                .getXMLReader();
        // create a SAXXMLHandler
        SAXXMLHANDLER saxHandler = new SAXXMLHANDLER();
        // store handler in XMLReader
        xmlReader.setContentHandler(saxHandler);
        // the process starts
        xmlReader.parse(new InputSource(is));
        // get the News list`
        setAdds = saxHandler.getIds();

    } catch (Exception ex) {
        Log.d("XML", "SAXXMLParser: parse() failed");
        ex.printStackTrace();
    }

    // return News list
    return setAdds;
}

}

我的SAX XML HANDLER:

public class SAXXMLHANDLER extends DefaultHandler {

    private List<XMLSetAdd> setAdds;
    private String tempVal;
    // to maintain context
    private XMLSetAdd setAdd;

    public SAXXMLHANDLER() {
        setAdds = new ArrayList<XMLSetAdd>();
    }

    public List<XMLSetAdd> getIds() {
        return setAdds;
    }

    // Event Handlers
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        // reset
        tempVal = "";
        if (qName.equals("skus")) {
            setAdd = new XMLSetAdd();
        }
    }

    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.equals("skus")) {
            setAdds.add(setAdd);
        } else if (qName.equals("id")) {
            setAdd.setId(tempVal);
        }
    }

}

我的XML SetAdd:

public class XMLSetAdd {

    public String getId() {
        return Id;
    }

    public void setId(String Id) {
        this.Id = Id;
    }

    private String Id;
}

我的异步类:

private class GetXMLTask extends AsyncTask<String, Void, List<XMLSetAdd>> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(List<XMLSetAdd> news) {

            try 
            {
                for (int i = 0; i < IdsL.size(); i++) 
                {
                    skusList.add(IdsL.get(i).getId());
                    Log.d("XML content",IdsL.get(i).getId());
                }

                skusQuery = new Bundle();
                skusQuery.putStringArrayList("ITEM_ID_LIST", skusList);

                GetAllSkusAsync runner = new GetAllSkusAsync();//Some Async to run after
                runner.execute();               
            } 
            catch (Exception ex) 
            {
                Log.d("Error Reading XML: ", ex.toString());
                Toast.makeText(
                        getApplicationContext(),"Connection Error!"
                        Toast.LENGTH_SHORT).show();
            }
        }

        /*
         * uses HttpURLConnection to make Http request from Android to download
         * the XML file
         */
        private String getXmlFromUrl(String urlString) {
            StringBuffer output = new StringBuffer("");
            try {
                InputStream stream = null;
                URL url = new URL(urlString);
                URLConnection connection = url.openConnection();

                HttpURLConnection httpConnection = (HttpURLConnection) connection;
                httpConnection.setRequestMethod("GET");
                httpConnection.connect();

                if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    stream = httpConnection.getInputStream();

                    BufferedReader buffer = new BufferedReader(new InputStreamReader(stream));
                    String s = "";
                    while ((s = buffer.readLine()) != null)
                        output.append(s);
                }
            } catch (Exception ex) {
                Log.d("Error in asyncTask XML: ", ex.toString());
                ex.printStackTrace();
            }
            return output.toString();
        }

        private List<XMLSetAdd> IdsL;

        @Override
        protected List<XMLSetAdd> doInBackground(String... urls) {
            IdsL = null;
            List<XMLSetAdd> myList = null;
            String xml = null;
            for (String url : urls) {
                xml = getXmlFromUrl(url);

                InputStream stream = new ByteArrayInputStream(xml.getBytes());
                IdsL = SAXXMLParser.parse(stream);

                myList = SAXXMLParser.parse(stream);
            }
            // stream.close();
            return IdsL;
        }
    }

我用来调用异步类的代码:

String URL = "http://someaddress/php/sku.xml";
GetXMLTask task = new GetXMLTask();
task.execute(new String[] { URL });

现在,当我运行此代码并记录结果时,我的列表返回基于我的xml文件的最后一个xml子项“ll”,其余的xml未添加到文件中。

列表应返回所有ID,但返回最后一个。

4 个答案:

答案 0 :(得分:3)

检查以下代码。编辑SAX XML HANDLER。

public class SAXXMLHANDLER extends DefaultHandler {

private List<XMLSetAdd> setAdds;
private String tempVal;
// to maintain context
private XMLSetAdd setAdd;

public SAXXMLHANDLER() {

}

public List<XMLSetAdd> getIds() {
    return setAdds;
}

// Event Handlers
public void startElement(String uri, String localName, String qName,
        Attributes attributes) throws SAXException {
    // reset
    tempVal = "";
    if (qName.equals("skus")) {
        setAdds = new List<XMLSetAdd>();

    }else if(qName.equals("id")){
         setAdd = new XMLSetAdd();
     }
}

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.equals("skus")) {

    } else if (qName.equals("id")) {
        setAdd.setId(tempVal);
        setAdds.add(setAdd);
    }
}

}

答案 1 :(得分:1)

原因是因为您只在endElementskus时才将项目添加到列表中。您应该为每个id添加一个元素,如下所示:

 public void endElement(String uri, String localName, String qName) throws SAXException {
        if (qName.equals("skus")) {
            // setAdds.add(setAdd); // dont add here..
        } else if (qName.equals("id")) {
            setAdd.setId(tempVal); // if ending with id
            setAdds.add(setAdd); // then add id to the list
        }
 }

<强>更新

 public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        // reset
        tempVal = "";
        if (qName.equals("id")) {
            setAdd = new XMLSetAdd(); // new item for each id
        }
 }

答案 2 :(得分:0)

   @Override
public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {
    super.startElement(uri, localName, qName, attributes);
    curentElement=localName;

    if(qName.equals("skus")){
       setAdd = new XMLSetAdd();
    }
}

 @Override
public void characters(char[] ch, int start, int length)
        throws SAXException {
    super.characters(ch, start, length);

    String value = new String(ch, start, length);
    if(curentElement.equals("id")){
        tempVal=value;  
}

   @Override
public void endElement(String uri, String localName, String qName)
        throws SAXException {
    super.endElement(uri, localName, qName);
    curentElement = "";
    if (localName.equals("id")) {
      setAdd.setId(tempVal);
    }else if(localName="skus"){
             setAdds.add(setAdd);
}

答案 3 :(得分:0)

试试这种方式

更新你的解析

public class SAXXMLHANDLER extends DefaultHandler {

    private List<XMLSetAdd> setAdds;
    private String tempVal;
    // to maintain context
    private XMLSetAdd setAdd;

    public SAXXMLHANDLER() {
        setAdds = new ArrayList<XMLSetAdd>();
    }

    public List<XMLSetAdd> getIds() {
        return setAdds;
    }

    // Event Handlers
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        // reset
        if (qName.equals("id")) {
            tempVal = "";
            setAdd = new XMLSetAdd();
        }
    }

    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.equals("id")) {
            setAdd.setId(tempVal);
            setAdds.add(setAdd);
        }
    }