Parse XML data through DOM parser. - android

I am struggling from many hours to parse some XMl data.
XML Data:
<?xml version="1.0" encoding="utf-8"?>
<data>
<status>200</status>
<description>OK</description>
<topcities>
<city>Ahmedabad</city>
<city>Bangalore</city>
<city>Chandigarh</city>
<city>Chennai</city>
<city>Cochin</city>
<city>Faridabad</city>
<city>Ghaziabad</city>
<city>Gurgaon</city>
<city>Hyderabad</city>
<city>Kolkata</city>
<city>Mumbai</city>
<city>Navi Mumbai</city>
<city>New Delhi</city>
<city>Noida</city>
<city>Pune</city>
<city>Thane</city>
</topcities>
<othercities>
<city>Agra</city>
<city>Ahmednagar</city>
<city>Ajmer</city>
<city>Akola</city>
<city>Allahabad</city>
<city>Ambala</city>
<city>Amravati</city>
<city>Amritsar</city>
<city>Anand</city>
<city>Aurangabad</city>
<city>Belgaum</city>
<city>Bharuch</city>
<city>Bhavnagar</city>
<city>Bhilai</city>
<city>Bhopal</city>
<city>Bhubaneswar</city>
<city>Bhuj</city>
<city>Bilaspur</city>
<city>Coimbatore</city>
<city>Dehradun</city>
<city>Dhanbad</city>
<city>Dharwad</city>
<city>Durgapur</city>
<city>Durg</city>
<city>Erode</city>
<city>Firozabad</city>
<city>Gandhidham</city>
<city>Gandhinagar</city>
<city>Goa</city>
<city>Guwahati</city>
<city>Gwalior</city>
<city>Haldwani</city>
<city>Himmatnagar</city>
<city>Howrah</city>
<city>Hubli</city>
<city>Indore</city>
<city>Jabalpur</city>
<city>Jaipur</city>
<city>Jalandhar</city>
<city>Jamnagar</city>
<city>Jamshedpur</city>
<city>Jodhpur</city>
<city>Kanpur</city>
<city>Kolhapur</city>
<city>Kollam</city>
<city>Kota</city>
<city>Kottayam</city>
<city>Kozhikode</city>
<city>Kurukshetra</city>
<city>Lucknow</city>
<city>Ludhiana</city>
<city>Madurai</city>
<city>Mangalore</city>
<city>Mathura</city>
<city>Meerut</city>
<city>Mehsana</city>
<city>Mohali</city>
<city>Mysore</city>
<city>Nagpur</city>
<city>Nanded</city>
<city>Nashik</city>
<city>Nellore</city>
<city>Panchkula</city>
<city>Panipat</city>
<city>Patiala</city>
<city>Patna</city>
<city>Pondicherry</city>
<city>Raipur</city>
<city>Rajkot</city>
<city>Ranchi</city>
<city>Ratnagiri</city>
<city>Rohtak</city>
<city>Saharanpur</city>
<city>Salem</city>
<city>Sangli</city>
<city>Satara</city>
<city>Shimla</city>
<city>Shillong</city>
<city>Siliguri</city>
<city>Sivakasi</city>
<city>Solapur</city>
<city>Srinagar</city>
<city>Surat</city>
<city>Thanjavur</city>
<city>Thrissur</city>
<city>Tirunelveli</city>
<city>Tirupati</city>
<city>Tirupur</city>
<city>Trichy</city>
<city>Trivandrum</city>
<city>Udaipur</city>
<city>Ujjain</city>
<city>Vadodara</city>
<city>Vapi</city>
<city>Valsad</city>
<city>Varanasi</city>
<city>Vellore</city>
<city>Vijayawada</city>
<city>Visakhapatnam</city>
<city>Visnagar</city>
<city>Warangal</city>
<city>Yamunanagar</city>
</othercities>
</data>
My Parsing Code:
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL);
// getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_TOP_CITY);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
//HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
NodeList children = e.getChildNodes();
for (int j = 0; j < children.getLength(); j++) {
Node child = children.item(j);
HashMap<String, String> map = new HashMap<String, String>();
if (child.getNodeName().equalsIgnoreCase(KEY_CITY)) {
Log.v("Data", parser.getValue(e, KEY_CITY));
map.put(KEY_CITY, parser.getValue(e, KEY_CITY));
}
menuItems.add(map);
}
But unfortunately I am getting only the first city(Ahmedabad) repeatedly. But I want all cities to show..
Can anyone please help ..
Thanks ..

Here's another implementation using the org.w3c.dom package. This code loads from a local file, but you could easily modify it to use a URL.
try
{
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File("test.xml"));
document.getDocumentElement().normalize();
System.out.println("Root element: " + document.getDocumentElement().getNodeName());
NodeList nodeList = document.getElementsByTagName("topcities");
System.out.println("-------------------------------");
for (int i=0; i<nodeList.getLength();i++)
{
Node node = nodeList.item(i);
System.out.println("Current Element: " + node.getNodeName());
if (node.getNodeType() == Node.ELEMENT_NODE)
{
// You would put your code to add the city to the map in place
// of the print statement.
System.out.println(node.getTextContent());
}
}
}
catch (SAXException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (ParserConfigurationException e)
{
e.printStackTrace();
}
By the way, that second for loop is redundant (unless the city element can have children.) You just need to loop through the list that you retrieved via getElementsByTagName.

Try this code.. The xml pull parser is better than other xml parsers
XmlPullParserFactory pullParserFactory;
try {
pullParserFactory = XmlPullParserFactory.newInstance();
XmlPullParser parser = pullParserFactory.newPullParser();
String file = "assets/name of your xml file";
InputStream in_s = this.getClass().getClassLoader().getResourceAsStream(file);
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
parser.setInput(in_s, null);
parseXML(parser);
} catch (XmlPullParserException e) {
} catch (IOException e) {
}
private void parseXML(XmlPullParser parser) throws XmlPullParserException,
IOException {
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
String cityName = null;
cityName = parser.getName();
if(eventType == XmlPullParser.START_TAG && name.equals("city"))
{
if(parser.nextText())
{
System.out.println("City: "+nextText().toString);
}
}
eventType = parser.next();
}
}

Related

How to parse xml data with attributes in Android? [duplicate]

I have a xml data like below:
<toplevel>
<CompleteSuggestion>
<suggestion data="madonna"/>
</CompleteSuggestion>
<CompleteSuggestion>
<suggestion data="madonna like a prayer"/>
</CompleteSuggestion>
<CompleteSuggestion>
<suggestion data="madonna like a virgin"/>
</CompleteSuggestion>
<CompleteSuggestion>
<suggestion data="madonna vogue"/>
</CompleteSuggestion>
<CompleteSuggestion>
<suggestion data="madonna la isla bonita"/>
</CompleteSuggestion>
<CompleteSuggestion>
<suggestion data="madonna frozen"/>
</CompleteSuggestion>
<CompleteSuggestion>
<suggestion data="madonna holiday"/>
</CompleteSuggestion>
<CompleteSuggestion>
<suggestion data="madonna music"/>
</CompleteSuggestion>
<CompleteSuggestion>
<suggestion data="madonna gimme all your love"/>
</CompleteSuggestion>
<CompleteSuggestion>
<suggestion data="madonna celebration"/>
</CompleteSuggestion>
</toplevel>
I am parsing this by using a XMLParser class below:
public class XMLParser {
// constructor
public XMLParser() {
}
/**
* Getting XML from URL making HTTP request
* #param url string
* */
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet(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;
}
/**
* Getting XML DOM element
* #param XML string
* */
public 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;
}
/** Getting node value
* #param elem element
*/
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
Log.e("in element","element");
if (elem.hasChildNodes()){
Log.e("in child","child nodes");
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
Log.e("in for","for loop");
child = elem.getFirstChild();
if( child.getNodeType() == Node.TEXT_NODE ){
Log.e("in if condition","if cond");
return elem.getNodeValue();
}
}
}
}
return "";
}
/**
* Getting node value
* #param Element node
* #param key string
* */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
}
Here is my Activity code:
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Log.e("string xml","hello"+xml);
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
Log.e("no. of items",""+i);
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
Log.e("names","hi"+parser.getValue(e, KEY_NAME));
menuItems.add(map);
}
I observed that my getElementValue( Node elem ) in XmLParser is always returning empty String. I think I need to change this method. I tried by changing some of the statements but didn't find any solution.

Parse XML and show it in TextView

I am making a quiz application. For the MCQ questions I have an XML, which I have parsed.
This is the XML:
<quiz>
<mchoice>
<question>Not a team sport for sure</question>
<id>1</id>
<option1>Cricket</option1>
<option2>Tennis</option2>
<option3>Rugby</option3>
<option4>Soccer</option4>
<answer>Tennis</answer>
</mchoice>
<mchoice>
<question>I am the biggest planet in the Solar System</question>
<id>2</id>
<option1>Saturn</option1>
<option2>Jupiter</option2>
<option3>Neptune</option3>
<option4>Pluto</option4>
<answer>Jupiter</answer>
</mchoice>
<mchoice>
<question>I am the closest star to the earth</question>
<id>3</id>
<option1>Milky way</option1>
<option2>Moon</option2>
<option3>Sun</option3>
<option4>North Star</option4>
<answer>Sun</answer>
</mchoice>
<mchoice>
<question>A number which is not prime</question>
<id>4</id>
<option1>31</option1>
<option2>61</option2>
<option3>71</option3>
<option4>91</option4>
<answer>91</answer>
</mchoice>
<mchoice>
<question>Which is correct?</question>
<id>5</id>
<option1>Foreine</option1>
<option2>Fariegn</option2>
<option3>Foreig</option3>
<option4>Foreign</option4>
<answer>Foreign</answer>
</mchoice>
</quiz>
This is the XML Parser class which I have used:
public class XMLParser {
// constructor
public XMLParser() {
}
/**
* Getting XML from URL making HTTP request
* #param url string
* */
public 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;
}
/**
* Getting XML DOM element
* #param XML string
* */
public 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;
}
/** Getting node value
* #param elem element
*/
public final 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 "";
}
/**
* Getting node value
* #param Element node
* #param key string
* */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
}
This is the activity from which I am calling the XML parser Class and adding the parsed data into an Arraylist having hashMap inside it:
// All static variables
static final String URL = "http://gujaratimandal.org/data.xml";
// XML node keys
static final String KEY_MCHOICE = "mchoice"; // parent node
static final String KEY_QUESTION = "question";
static final String KEY_ID = "id";
static final String KEY_OPTION1 = "option1";
static final String KEY_OPTION2 = "option2";
static final String KEY_OPTION3 = "option3";
static final String KEY_OPTION4 = "option4";
static final String KEY_ANSWER = "answer";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_MCHOICE);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_MCHOICE, parser.getValue(e, KEY_MCHOICE));
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_QUESTION, parser.getValue(e, KEY_QUESTION));
//map.put(KEY_QUESTION, parser.getValue(e, KEY_QUESTION));
map.put(KEY_OPTION1, parser.getValue(e, KEY_OPTION1));
map.put(KEY_OPTION2, parser.getValue(e, KEY_OPTION2));
map.put(KEY_OPTION3, parser.getValue(e, KEY_OPTION3));
map.put(KEY_OPTION4, parser.getValue(e, KEY_OPTION4));
map.put(KEY_ANSWER, parser.getValue(e, KEY_ANSWER));
// adding HashList to ArrayList
menuItems.add(map);
for (HashMap.Entry<String, String> entry : map.entrySet()) {
String display_id=entry.getKey();
String display_question = entry.getValue();
makeAToast( ""+display_id+":"+ display_question);
}
}
makeAToast(""+menuItems.size());
}
public void makeAToast(String str) {
Toast toast = Toast.makeText(this,str, Toast.LENGTH_LONG);
toast.setGravity(Gravity.BOTTOM, 0, 0);
toast.setDuration(1000000);
toast.show();
}
The problem is that, the data is getting retrieved but not in the desired way.
I want to retrieve the data in the following format:
Such that I can populate these TextViews with the data from every question:
What should I do?
make one string in you public class activity
String keyoption,keyoption2,name;
and
for (int i = 0; i < nl.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
keyoption = parser.getValue(e, KEY_OPTION1);
keyoption2 = parser.getValue(e, KEY_OPTION2);
map.put(KEY_OPTION1, keyoption);
map.put(KEY_OPTION2, keyoption2);
}
name.setText(keyoption);
Create an xml file for the layout like that you mentioned.
Its simple.
Create a LinearLayout as the root of your xml. (this is anyways the default) android:gravity="center"
Looks like you need 5 textViews inside the LinearLayout. One for the question. 4 for your options. all of them with android:gravity="center_horizontal"
One EditText in the end for the answer.

How to parse particular attribute from XML for android 4.0

I want to access particular attributes from xml like in this example there are 2 image tag but 2 different attributes size small and size medium so how can i access medium
<image size="small">http://userserve-ak.last.fm/serve/34/62210477.png</image><image size="medium">http://userserve-ak.last.fm/serve/64/62210477.png</image>
I tried this it works on lower android version but it wont work on 4.0
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
try {
expr = xpath.compile("//image[#size=\"large\"]");
nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
here is Full code
public class loadSomeStuff extends AsyncTask<Void, Void, String>
{
XPathExpression expr;
NodeList nl;
int i;
String name="test";
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
final String KEY_NAME = "name";
final String KEY_IMAGE ="image";
//final String KEY_COST = "cost";
//final String KEY_DESC = "description";
String URL = "http://ws.audioscrobbler.com/2.0/?method=artist.search&artist=enrique_iglesias&api_key=b25b959554ed76058ac220b7b2e0a026&limit=" + 1 + "&page=" + 1;
XmlParser parser = new XmlParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
//XPathFactory xPathfactory = XPathFactory.newInstance();
//XPath xpath = xPathfactory.newXPath();
//try {
// expr = xpath.compile("//image[#size=\"large\"]");
//nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
NodeList nl = doc.getElementsByTagName("artist");
for (i = 0; i < nl.getLength(); i++)
{
Element e = (Element) nl.item(i);
name = parser.getValue(e, KEY_NAME);// name child value
image = parser.getValue(e, KEY_IMAGE);
System.out.print(image);
Log.v(image, "image url");
return image;
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
URL thumb_u;
try {
thumb_u = new URL(result);
Drawable thumb_d = Drawable.createFromStream(thumb_u.openStream(), "src");
Toast toast = Toast.makeText(myActionbar.this, image, Toast.LENGTH_LONG);
toast.show();
icon.setImageDrawable(thumb_d);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
here is My Xmlparserfile in which my getvalue and get elements are defined
public 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 DOM
return doc;
}
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
public final 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 "";
}
}
Try this:
XMLParser parser = new XMLParser();
String URL = "http://ws.audioscrobbler.com/2.0/?method=artist.gettopalbums&artist=akon&api_key=your_api_key";
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName("album");
for (int i = 0; i < nl.getLength(); i++) {
Element e = (Element) nl.item(i);
Log.e("name", parser.getValue(e, "name"));
NodeList k = e.getElementsByTagName("image");
for (int j = 0; j < k.getLength(); j++) {
Element e1 = (Element) k.item(j);
if(e1.getAttribute("size").equals("large"))
Log.e("ImageURL", parser.getValue(e1, "image"));
}
}

Parse CDATA with XMLParser in this specific case for ANDROID

I've seen quite a few posts about this, but actually I did not get any to work. I am building a simple TV guide android application. I simply Use RSS from a tvprofil.net to show whats on TV today. The problem is, I do not know how to Parse CDATA in XML. I am using some standard parser with DOM... at least I think so..
This is a bit of XML:
.
.
.
<item>
<title>RTS1 14.08.2012</title>
<pubDate>Tue, 14 Aug 2012 06:00:00</pubDate>
<content:encoded><![CDATA[06:00 Vesti<br>06:05 Jutarnji program<br>08:00 Dnevnik
<br>8:15 Jutarnji Program<br>09:00 Vesti ... ]]></content:encoded>
</item>
.
.
.
now, this is my main app:
public class Main extends ListActivity {
// All static variables
static final String URL = "http://tvprofil.net/rss/feed/channel-group-2.xml";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_NAME = "title";
static final String KEY_DATE = "pubDate";
static final String KEY_DESC = "content:encoded";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<HashMap<String,String>> menuItems = new ArrayList<HashMap<String,String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); //get XML
Document doc = parser.getDomElement(xml); // get DOM elem.
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
//loop
for (int i=0; i< nl.getLength(); i++){
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
//add to map
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_DATE, parser.getValue(e, KEY_DATE));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
// hash => list
menuItems.add(map);
}
ListAdapter adapter = new SimpleAdapter(this, menuItems, R.layout.list_item,
new String[]{KEY_NAME, KEY_DESC, KEY_DATE}, new int[]{
R.id.name, R.id.description, R.id.date
});
setListAdapter(adapter);
//singleView
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
String name = ((TextView)view.findViewById(R.id.name)).getText().toString();
String date = ((TextView)view.findViewById(R.id.date)).getText().toString();
String description = ((TextView)view.findViewById(R.id.description)).getText().toString();
//intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_NAME, name);
in.putExtra(KEY_DATE, date);
in.putExtra(KEY_DESC, description);
startActivity(in);
}
});
}
}
and the parser class:
public class XMLParser {
// constructor
public XMLParser() {
}
/**
* Getting XML from URL making HTTP request
* #param url string
* */
public 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;
}
/**
* Getting XML DOM element
* #param XML string
* */
public 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;
}
/** Getting node value
* #param elem element
*/
public final 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 "";
}
/**
* Getting node value
* #param Element node
* #param key string
* */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
}
there is one more class for Single menu item.. but I think it's irrelevant in this case.
Now, I'd just like to see no HTML tags after parsing it and dealing with CDATA...
Anyone got idea about this one?
Add this
dbf.setCoalescing(true);
where dbf is
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
First add this method
public String getCharacterDataFromElement(Element e, String str) {
NodeList n = e.getElementsByTagName(str);
Element e1=(Element) n.item(0);
Node child = e1.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}
Call the above method as so-
map.put(KEY_DESC, parser.getCharacterDataFromElement(e, KEY_DESC));
This should get you the CDATA in String format. HOpe this helps
getTextContent.
This attribute returns the text content of this node and its
descendants
getNodeValue()
The value of this node, depending on its type;
usually you shouled use getTextContent.
zg_spring's answer worked perfectly for me when I needed to extract image URLs from CDATA in a set of "description" xml elements:
//Get the content of all "item" elements
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(xml)));
NodeList nlDetails = doc.getElementsByTagName("item");
//Loop through elements and extract content of "description" elements
for(int k = 0; k < numDetails; k++) {
Element nDetails = (Element)nlDetails.item(k);
NodeList nlCoverURL = nDetails.getElementsByTagName("description");
Node nCoverURL = nlCoverURL.item(0);
String sCoverURL = nCoverURL.getTextContent();
//Isolate the relevant part of the String and load it into an ArrayList
String[] descriptionContent = sCoverURL.split("\"");
String s = descriptionContent[11]
alImages.add(s);
}

How to parse an XML file in an Android app

I am trying to parse an XML file as below
<Subject>
<chapter>
<Question>abc</Question>
<answer>avksn</answer>
</chapter>
<chapter>
<Question>def</Question>
<answer>avksn</answer>
</chapter>
<chapter>
<Question>ccsv</Question>
<answer>avksn</answer>
</chapter>
</Subject>
in this i am able to count the number of chapter. the number of chapter is equal to number of question and answer. i have also placed a button named as ok in my layout.
now i want to display the first question and after clicking ok i want to display the second question and it goes till the end. When i reached the last question i want to move to a new activity.
how to perform this, pls help me
Read the xml into a InputStream and then:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse([the InpuTstream]);
Then you can use doc like:
if(doc.getElementsByTagName("GeometryCollection").getLength()>0){
org.w3c.dom.Node parent_node = doc.getElementsByTagName("GeometryCollection").item(0);
NodeList nl = parent_node.getChildNodes();
for(int i = 0;i<nl.getLength();i++){
...
Read the XML into a document ( v = the xml string )
public Document XMLfromString(){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(v));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
System.out.println("Wrong XML file structure: " + e.getMessage());
return null;
} catch (IOException e) {
e.printStackTrace();
}
return doc;
}
Then get the element like so:
/** Returns element value
* #param elem element (it is XML tag)
* #return Element value otherwise empty String
*/
public final static String getElementValue( Node elem ) {
Node kid;
if( elem != null){
if (elem.hasChildNodes()){
for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
if( kid.getNodeType() == Node.TEXT_NODE ){
return kid.getNodeValue();
}
}
}
}
return "";
}
How to use:
Document doc = x.XMLfromString();
NodeList nodes = doc.getElementsByTagName("result");
for (int i = 0; i < nodes.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element)nodes.item(i);
map.put("id", x.getValue(e, "orgid"));
map.put("bedrijf", x.getValue(e, "naam"));
map.put("plaats", x.getValue(e, "plaats"));
mylist.add(map);
}

Categories

Resources