How to parse a xml type HTTPResponse in Android

2019-04-12 16:24发布

问题:

I have an android application where I use POST method to get a response. here is my code:

..........................................
HttpResponse httpResponse = httpclient.execute(httppost);
HttpEntity resEntity =  httpResponse.getEntity();

this works fine and i get a response in xml format but i want to parse that xml file and get the node values. i tried this :

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource());
doc.getDocumentElement().normalize();

but I don't know what should give to new InputSource() because I have to use a XML type HTTPResponse not a url.

Thanks !!!

回答1:

ok thanks everyone for the replies. i just found out a way to overcome my problem. http://www.rgagnon.com/javadetails/java-0573.html



回答2:

try

InputStream is = resEntity .getContent()
Document doc = db.parse(is);


回答3:

You can use any XML parser like SAX to parse ur XML Data



回答4:

if your response in xml string format follow

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is=new InputSource();
is.setCharacterStream(new StringReader(xmlString(ur response)))
Document doc = db.parse(is);


回答5:

            getsyncFlag(String feedData) {

            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();
            xr.setContentHandler(this);
            InputSource is=new InputSource();
            is.setCharacterStream(new StringReader((feedData)));
            xr.parse(is);
}