如何在android中使用SAX Parser进行嵌套解析

时间:2012-05-16 10:03:57

标签: android saxparser

我有一个像这样的xml:

<channel>
    <item>
      <link>http://uopnews.unipune.ac.in/Lists/Calendar/DispForm.aspx?ID=14</link>
      <description><![CDATA[<div><b>Location:</b> PUMBA Auditorium - University of  Pune</div> <div><b>Start Time:</b> 5/15/2012 11:00 AM</div>
<div><b>End Time:</b> 5/15/2012 2:00 PM</div>
<div><b>Description:</b> <div>General B. C. Joshi Memorial Lecture 2012- Perspective on War in the 21st Century - By Lt. Gen. A. K. Singh</div></div>
<div><b>Attachments:</b> <a href="http://uopnews.unipune.ac.in/Lists/Calendar/Attachments/14/bcjoshi2012[1].pdf">http://uopnews.unipune.ac.in/Lists/Calendar/Attachments/14/bcjoshi2012[1].pdf</a><br><a href=""></a></div>
]]></description>  
    </item>
</channel>

我可以使用SAX Parser解析说明标签这里是我的SAXhandler类。

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import android.R.string;
import android.util.Log;

public class XMLParsingHandler extends DefaultHandler {
    private static final String NEW_DATA_SET = "image";
    private String currentValue = "";
    private String currentTag = "";
    private HashMap<String, Object> root;
    private HashMap<String, String> child;
    private String[] tagArray = null;
    private ArrayList<HashMap<String, String>> arraylist  = new ArrayList<HashMap<String, String>>();
    private String describe; 

    public XMLParsingHandler(String[] tagArray) {
        this.tagArray = tagArray;
    }

    public void parseContent(String urlStr) {
        try {
            URL url = new URL(urlStr);
            SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
            SAXParser saxParser = saxParserFactory.newSAXParser();
            XMLReader xmlReader = saxParser.getXMLReader();
            xmlReader.setContentHandler(this);
            xmlReader.parse(new InputSource(url.openStream()));
            Log.d("PRASER", "Afer parsering done" + arraylist);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void startDocument() throws SAXException {
        super.startDocument();
        root = new HashMap<String, Object>();
        System.out.println("root=" + root);
    }

    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        super.startElement(uri, localName, qName, attributes);
        Log.d("tag", "StartElement started here");
        currentTag = localName;
        Log.d("start", "in start doc current atg---------: " + currentTag);
        if (localName.equals(NEW_DATA_SET)) {
            child = new HashMap<String, String>();
            currentValue = new String();
        }

            describe=new String();

    }

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


        currentValue = new String(ch, start, length);
        Log.d("other", "in CHARACTER : CurrentValue=---------" + currentValue
                + " currentTag-------" + currentTag);
        if(currentTag.equals("description") ) {
            String str=     new String(ch, start, length);
            //describe=new String();
            describe=describe+""+currentValue;
            Log.d("describe", "in CHARACTER : describe=---------" + describe);

        }
    }

    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        super.endElement(uri, localName, qName);
        Log.d("end", "currentTag:"+currentTag+"------currentValue"+currentValue);
        if(child!=null)
        {
        for (int i = 0; i < tagArray.length; i++) {
            if (currentTag.equals("description")){
                child.put(currentTag, currentValue);
            }
            if (currentTag.equals(tagArray[i]))
            {
                child.put(currentTag, currentValue);
                Log.d("tagarray","currentTag="+ currentTag+"currentValue:"+currentValue);

                currentValue=null;
                currentValue=new String();
                currentTag=null;
                currentTag=new String();
            }

        }

        if (localName.equals(tagArray[tagArray.length - 1])) {
            arraylist.add(child);
            child=null;
            child=new HashMap<String, String>();
        }


        }
    }

    @Override
    public void endDocument() throws SAXException {
        super.endDocument();
        Log.d("tag", "in end doc");

    }


    public ArrayList<HashMap<String, String>> getArraylist() {
        return arraylist;
    }


    public void setArraylist(ArrayList<HashMap<String, String>> arraylist) {
        this.arraylist = arraylist;
    }
    @Override
    public String toString() {
        return arraylist.toString();
    }

}

我打电话给它:

userMap = new HashMap<String, String>();

        XMLParsingHandler x = new XMLParsingHandler(tagArray);
        x.parseContent(url);
        System.out.println("Element FOund");
        userMap = x.getArraylist().get(0);
        System.out.println("Map " + userMap);

这里我的userMap仅在显示空值后才打印值到描述标签。我需要描述中的所有数据。有什么办法吗?

1 个答案:

答案 0 :(得分:1)

找到下面的sax解析器代码

public class IndianNewsHandler implements ContentHandler {
private String value = "";
private Item item = null;
private TextView tvRef = null;
private Activity myActivity = null;

private static IndianNewsHandler mIndianNewsHandler;

public static IndianNewsHandler getInstance() {
    if (mIndianNewsHandler == null) {
        mIndianNewsHandler = new IndianNewsHandler();
    }
    return mIndianNewsHandler;
}

private IndianNewsHandler() {

}

private ArrayList<Item> content = new ArrayList<Item>();
// private ArrayList<String> myList = new ArrayList<String>();
private boolean STATUS_PARSE = true;
private boolean ITEM_STATUS = false;

public ArrayList<Item> getData() {
    return content;
}

public void startElement(String namespaceURI, String localName,
        String qName, Attributes atts) throws SAXException {

    if (STATUS_PARSE) {
        this.value = localName;

        if (localName.equals("item")) {

            item = new Item();
            ITEM_STATUS = true;
        }

    }
}

public void characters(char[] text, int start, int length)
        throws SAXException {
    if (STATUS_PARSE && ITEM_STATUS) {
        StringBuffer buffer = new StringBuffer();
        buffer.append(text, 0, length);

        if (buffer != null) {

            if (this.value.equals("title")) {
                System.out.println("I am in title"
                        + buffer.toString().trim());
                if (buffer.toString().trim().length() > 1)
                    item.setTitle(buffer.toString().trim());

            } else if (value.equals("description"))

            {

                String url = buffer.toString().trim();

                try {

                    if (url.contains("img src=")) {
                        final String url_string = url.split("img src=")[1]
                                .split(">")[0].replace("'", "");
                        System.out.println("FInal URL :" + url_string);
                        if (url_string != null) {
                            //here i am creating async task for convert image
                            new CovertingImageToByte(url_string).execute();


                            if (buffer.toString().trim().length() > 1) {
                                String des = buffer.toString().split(">")[1];
                                item.setDes(des);
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
class CovertingImageToByte extends AsyncTask<String,Integer, String>{
    String imageUrl;
    public CovertingImageToByte(String urlString) {
        this.imageUrl=urlString;
    }

    @Override
    protected String doInBackground(String... params) {
        try {
            InputStream is = new URL(imageUrl)
                    .openStream();

            Bitmap bitmap = BitmapFactory
                    .decodeStream(is);
            byte[] mybyt = null;
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(CompressFormat.PNG,
                    0, stream);
            mybyt = stream.toByteArray();

            System.out.println("test"
                    + mybyt.length);

            item.setImg(mybyt);
            // System.out.println("Finallly List123 size   ::::::::::"+content.get(0).getImg().length);

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
                return null;
    }

}

public void endElement(String namespaceURI, String localName, String qName)
        throws SAXException {
    if (STATUS_PARSE) {
        if (localName.equals("item")) {
            content.add(item);
        }

        if (content.size() >= 15) {
            STATUS_PARSE = false;
        }
    }

}

@Override
// do nothing methods
public void setDocumentLocator(Locator locator) {
}

public void startDocument() throws SAXException {
}

public void endDocument() throws SAXException {
    System.out.println("Finallly List size   ::::::::::" + content.get(1));
}

public void startPrefixMapping(String prefix, String uri)
        throws SAXException {
}

public void endPrefixMapping(String prefix) throws SAXException {
}

public void skippedEntity(String name) throws SAXException {
}

public void ignorableWhitespace(char[] text, int start, int length)
        throws SAXException {
}

public void processingInstruction(String target, String data)
        throws SAXException {
}

}