Problem when parsing xml string in java
I'm writing an android application, and I would like to get an xml string from web and get all info it contains. First of all, i get the string (this code works):
URL url = new URL("here my adrress");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String myData = reader.readLine();
reader.close();
Then, I use DOM:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(myData));
Still no problem. When I write
Document doc = db.parse(is);
the application doesn't do anything more. It stops, without errors. Can someone please tell me what's going开发者_开发知识库 on?
I wouldn't know why your code doesn't work since there is no error but I can offer alternatives.
First, I am pretty sure your new InputStream "is" is unnecessary. "parse()" can take "url.openStream()" or "myData" directly as an argument.
Another cause of error could be that your xml data has more than one line(I know you said that the first part of your code worked but I'd rather mention it, just to be sure). If so, "reader.readLine()" will only get you a part of your xml data.
I hope this will help.
Use SAXParser instead of DOM parser. SAXParser is more efficient than DOM parser. Here is two good tutorials on SAXParser 1. http://www.androidpeople.com/android-xml-parsing-tutorial-using-saxparser 2. http://www.anddev.org/parsing_xml_from_the_net_-_using_the_saxparser-t353.html
Use XmlPullParser
, it's very fast. Pass in the string from the web and get a hashtable with all the values.
public Hashtable<String, String> parse(String myData) {
XmlPullParser parser = Xml.newPullParser();
Hashtable<String, String> responseFromServer = new Hashtable<String, String>();
try {
parser.setInput(new StringReader (responseString));
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if(eventType == XmlPullParser.START_TAG) {
String currentName = parser.getName();
String currentText = parser.nextText();
if (currentText.trim().length() > 0) {
responseFromServer.put(currentName, currentText);
}
}
eventType = parser.next();
}
} catch (Exception e) {
e.printStackTrace();
}
return responseFromServer;
}
精彩评论