Reputation: 583
I have an online XML like this:
<rootxml>
<url src="sdfsdfsdfsdfs" />
<url src="sdfsdfsdfsdfs" />
<url src="sdfsdfsdfsdfs" />
<url src="sdfsdfsdfsdfs" />
<url src="sdfsdfsdfsdfs" />
<url src="sdfsdfsdfsdfs" />
<url src="sdfsdfsdfsdfs" />
and so on...
</rootxml>
It contains like thousands of and I tried to use SAXParser on this one but it takes 30-40 seconds to parse the XML. It is very slow for my sample app.
Upvotes: 0
Views: 230
Reputation: 583
Thank you all for you help. After spending almost 10 hours on this one, I realized that what I really wanted is the attribute value not the actual value of the node. By using the code suggested by Saching, I came up with the following solution:
for (int i = 0; i < nl.getLength(); i++){
Element e = (Element) nl.item(i);
String value = e.getAttribute("src");
}
And it worked. Thanks again.
Upvotes: 0
Reputation: 573
String Xmlresponse=getXmlFromUrl(url);
Document mDocument =getDomElement(Xmlresponse);
NodeList mNodeResponse = mDocument.getElementsByTagName("rootxml");
for (int i = 0; i < mNodeResponse.getLength(); i++) {
Element e = (Element) mNodeResponse.item(i);
String url=getValue(e, "url");
}
private String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
after get xml response so get Document Element
//here pass String xml is your response
private Document getDomElement(String xml) {
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return doc;
}
public final static String getElementValue(Node elem) {
Node child;
if (elem != null) {
if (elem.hasChildNodes()) {
for (child = elem.getFirstChild(); child != null; child = child
.getNextSibling()) {
if (child.getNodeType() == Node.TEXT_NODE) {
return child.getNodeValue();
}
}
}
}
return "";
}
public static String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return getElementValue(n.item(0));
}
Upvotes: 0