In my application i am receiving the below Httpresponse from a webservice in xml format.
<?xml version="1.0" encoding="UTF-8"?>
<results>
<result>
<status>0</status>
<messageid>213123</messageid>
<destination>1234567890</destination>
</result>
</results>
I tried parsing the response in the below format :
private void parseXML(XmlPullParser parser) throws XmlPullParserException,IOException
{
ArrayList<SMSResponse> products = null;
int eventType = parser.getEventType();
SMSResponse currentProduct = null;
while (eventType != XmlPullParser.END_DOCUMENT){
Log.e("ENTER-", "while loop");
String name = null;
switch (eventType){
case XmlPullParser.START_DOCUMENT:
products = new ArrayList<SMSResponse>();
Log.e("ENTER-", "swicth case -1");
break;
case XmlPullParser.START_TAG:
name = parser.getName();
Log.e("start name", name);
if(name.equals("results"))
{
Log.e("start name", name);
}
else if(name.equals("result"))
{
Log.e("start name", name);
currentProduct = new SMSResponse();
}
else if(name.equals("status"))
{
Log.e("start name", name);
System.out.println("status value==");
currentProduct.status = parser.getProperty(name).toString();
}
else if(name.equals("messageid"))
{
Log.e("start name", name);
System.out.println("messageid value=="+ parser.getProperty(name));
currentProduct.messageid = parser.getProperty(name).toString();
}
else if(name.equals("destination"))
{
Log.e("start name", name);
System.out.println("destination value=="+ parser.getProperty(name));
currentProduct.destination = parser.getProperty(name).toString();
}
break;
case XmlPullParser.END_TAG:
name = parser.getName();
Log.e("end name", name);
// Log.e("ENTER-", "switch case-3");
if (name.equalsIgnoreCase("results") ){
Log.e("end name", name);
products.add(currentProduct);
}
}
eventType = parser.next();
}
Log.e("Array", products.toString());
// printProducts(products);
}
But i am getting null response as the value.
How do i extract the value of the xml header?
Please Help ! Thanks in Advance!
Following is the code snippet for handling XML operations. I am using XML parser class so far we built and looping through each XML element and getting the child data.
static final String KEY_RESULT = "result"; // parent node
static final String KEY_STATUS = "status";
static final String KEY_MESSAGE_ID = "messageid";
static final String KEY_DESC = "description";
XMLParser parser = new XMLParser();
//xml getting from url
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_RESULT);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
String name = parser.getValue(e, KEY_STATUS); // name child value
String cost = parser.getValue(e, KEY_MESSAGE_ID); // cost child value
String description = parser.getValue(e, KEY_DESC); // description child value
}
Related
My XML file is something like this:
<Items>
<Nested_item>
<id>1</id>
<name>nested</name>
<description>
<desc_item>1</desc_item>
<desc_item>2</desc_item>
<desc_item>3</desc_item>
</description>
</Nested_item>
<Nested_item>
<id>2</id>
<name>nested2</name>
<description>
<desc_item>1</desc_item>
<desc_item>2</desc_item>
<desc_item>3</desc_item>
</description>
</Nested_item>
<Nested_item>
<id>3</id>
<name>nested3</name>
<description>
<desc_item>1</desc_item>
<desc_item>2</desc_item>
<desc_item>3</desc_item>
</description>
</Nested_item>
</Items>
and I have class Items with atributes which I've putted into ArrayList, I've managed to parse all atributes except desc_item (which I need as ArrayList for every Item object). How can I tell parser to take only third item, for example, and to get those desc_item values as String?
I found solution to my problem, i have parsed inner data and after that i have parsed particular data:
private ArrayList<Proizvod> parseXML (XmlPullParser parser) throws XmlPullParserException, IOException {
ArrayList<Proizvod> proizvodLista = null;
int eventType = parser.getEventType();
Proizvod proizvod = null;
while(eventType != XmlPullParser.END_DOCUMENT){
String name;
switch (eventType){
case XmlPullParser.START_DOCUMENT:
proizvodLista = new ArrayList<Proizvod>();
break;
case XmlPullParser.START_TAG:
name = parser.getName();
//System.out.println(name);
if(name.equals("Proizvod")){
proizvod = new Proizvod();
proizvod.setId(parser.getAttributeValue(null, "id"));
}else if(proizvod != null){
if(name.equalsIgnoreCase("ime_proizvoda")){
proizvod.setIme_proizvoda(parser.nextText());
}else if(name.equalsIgnoreCase("vrsta_proizvoda")){
proizvod.setVrsta_proizvoda(parser.nextText());
}else if(name.equalsIgnoreCase("merna_jedinica")){
proizvod.setVrsta_proizvoda(parser.nextText());
}else if(name.equalsIgnoreCase("Prodavnice")){
proizvod.setLista_prodavnica(parsing(parser));
}
}
break;
case XmlPullParser.END_TAG:
name = parser.getName();
if(name.equalsIgnoreCase("proizvod")&& proizvod !=null){
proizvodLista.add(proizvod);
}
}
eventType = parser.next();
}
return proizvodLista;
}
private ArrayList<String> parsing (XmlPullParser parser) throws XmlPullParserException, IOException {
String print = null;
int eventType = parser.getEventType();
ArrayList<String> lista = new ArrayList<String>();
while(eventType != XmlPullParser.END_DOCUMENT){
String name = parser.getName();
if(name.equalsIgnoreCase("Prodavnice")){break;}
else{
if(eventType==XmlPullParser.START_TAG){
print = parser.nextText();
lista.add(print);
System.out.println(print);
}
}
eventType = parser.next();
}
return lista;
}
And my XML looks like this:
<?xml version="1.0" encoding="utf-8"?>
<Proizvodi>
<Proizvod id="1">
<ime_proizvoda>Mleko</ime_proizvoda>
<vrsta_proizvoda>mlecni proizvod</vrsta_proizvoda>
<merna_jedinica>litar</merna_jedinica>
<Prodavnice>
<Prodavnica>1</Prodavnica>
<Prodavnica>3</Prodavnica>
<Prodavnica>4</Prodavnica>
</Prodavnice>
</Proizvod>
<Proizvod id="2">
<ime_proizvoda>Hleb</ime_proizvoda>
<vrsta_proizvoda>Pekarski proizvod</vrsta_proizvoda>
<merna_jedinica>gram</merna_jedinica>
<Prodavnice>
<Prodavnica>1</Prodavnica>
<Prodavnica>2</Prodavnica>
<Prodavnica>3</Prodavnica>
</Prodavnice>
</Proizvod>
<Proizvod id="3">
<ime_proizvoda>Suvi vrat</ime_proizvoda>
<vrsta_proizvoda>Mesna preradjevina</vrsta_proizvoda>
<merna_jedinica>gram</merna_jedinica>
<Prodavnice>
<Prodavnica>2</Prodavnica>
<Prodavnica>3</Prodavnica>
<Prodavnica>4</Prodavnica>
</Prodavnice>
</Proizvod>
<Proizvod id="4">
<ime_proizvoda>Pecenica</ime_proizvoda>
<vrsta_proizvoda>Mesna preradjevina</vrsta_proizvoda>
<merna_jedinica>100 grama</merna_jedinica>
<Prodavnice>
<Prodavnica>1</Prodavnica>
<Prodavnica>2</Prodavnica>
<Prodavnica>4</Prodavnica>
</Prodavnice>
</Proizvod>
I'm trying to make an app for a podcast. My end goal is for a user to be able to click on an episode in a list (which is generated from an RSS feed) and then have the audio play (which is also retrieved from the RSS feed) My problem is with parsing the XML from the RSS feed. I can't seem to figure out how to get the URL out of the enclosure tag for the mp3. Any help would be appreciated. Here is my parsing class
private String data;
private ArrayList<Episodes> mEpisodes;
public ParseEpisodes(String xmlData) {
this.data = xmlData;
mEpisodes = new ArrayList<>();
}
public ArrayList<Episodes> getEpisodes() {
return mEpisodes;
}
public boolean process(){
boolean status = true;
Episodes currentRecord = null;
boolean inEntry = false;
String textValue = "";
String urlValue = "";
try{
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader(this.data));
int eventType = xpp.getEventType();
while(eventType != XmlPullParser.END_DOCUMENT){
String tagName = xpp.getName();
switch(eventType){
case XmlPullParser.START_TAG:
//Log.d("ParseEpisodes", "Starting tag for " + tagName);
if(tagName.equalsIgnoreCase("item")){
inEntry = true;
currentRecord = new Episodes();
}
break;
case XmlPullParser.TEXT:
textValue = xpp.getText();
urlValue = xpp.getText();
break;
case XmlPullParser.END_TAG:
//Log.d("ParseEpisodes", "Ending tag for " + tagName);
if(inEntry){
if(tagName.equalsIgnoreCase("item")){
mEpisodes.add(currentRecord);
inEntry = false;
}else if(tagName.equalsIgnoreCase("title")){
currentRecord.setTitle(textValue);
}else if(tagName.equalsIgnoreCase("enclosure")){
currentRecord.setLink(urlValue);
}
}
break;
}
eventType = xpp.next();
}
}catch (Exception e){
status = false;
e.printStackTrace();
}
return true;
}
here is the xml
<item>
<title>Episode 52 - Facebook Nukes The Show</title>
<link>https://greynoi.se/podcasts/episode-52-facebook-nukes-the-show</link>
<enclosure url="http://greynoi.se/episodes/ep79_m.mp3" length="43312404" type="audio/mpeg"/>
<pubDate>Fri, 15 Jul 2016 15:22:24 -0700</pubDate>
<category>1</category>
<source url="https://greynoi.se">The GR3YNOISE Podcast</source>
<itunes:subtitle>Episode 52 - Facebook Nukes The Show</itunes:subtitle>
<itunes:summary>Episode 52 - Facebook Nukes The Show</itunes:summary>
<content:encoded><![CDATA[Episode 52 - Facebook Nukes The Show"}]]></content:encoded>
<guid>https://greynoi.se/podcasts/episode-52-facebook-nukes-the-show</guid>
</item>
So you want the url after the enclosure url= tag?
If that is the case it is very easy. Just use substrings to find and get the url.
Something like this should work.
int urlTagStart = text.indexOf("<enclosure url="");
int urlTagEnd = text.indexOf(".mp3");
String url = text.substring(urlTagStart + 16, urlTagEnd + 4)
Try this:
...
YOUR CODE
...
while(eventType != XmlPullParser.END_DOCUMENT){
String tagName = xpp.getName();
if (tagName.equalsIgnoreCase("enclosure")) {
int attributeCount = xpp.getAttributeCount();
for(int i = 0; i<attributeCount; i++){
String attrib = xpp.getAttributeName(i);
if(attrib && attrib.equalsIgnoreCase("url")){
String url = xpp.getAttributeValue(i);
}
}
}
if (url != null && !url.isEmpty() && !url.equals("null")) {
Log.d("ParseEpisodes", "URL to mp3: " + url);
}
...
THE REST OF YOUR CODE
...
}
The solution to this ended up being pretty simple. All I needed to do was delete
urlValue = xpp.getText();
from the
case XmlPullParser.TEXT:
Then change
else if(tagName.equalsIgnoreCase("enclosure")){
urlValue = xpp.getAttributeValue(0);
currentRecord.setLink(urlValue);
}
in the
case XmlPullParser.END_TAG:
I'm trying to traverse a nested XML string in Android that looks like this:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Results>
<Result>
<Questions>
<Question>Where can I get the local variable</Question>
<Answer>In the local method</Answer>
<AverageRating>3.0</AverageRating>
</Questions>
<Keywords>
<Keyword>Methods</Keyword>
<Keyword>Returns</Keyword>
<Keyword>Void</Keyword>
</Keywords>
</Result>
<Result>
<Questions>
<Question>How can I do a nested for loop</Question>
<Answer>Easy</Answer>
<AverageRating>2.5</AverageRating>
</Questions>
<Keywords>
<Keyword>Methods</Keyword>
<Keyword>Returns</Keyword>
<Keyword>Void</Keyword>
<Keyword>Methods</Keyword>
<Keyword>Returns</Keyword>
</Keywords>
</Result>
with the following Android code:
try
{
//Creates the document
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(serverResult)));
//optional, but recommended
//read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
document.getDocumentElement().normalize();
//Look at root node's type (e.g. <query> or <login> or <add>)
String rootNode = document.getDocumentElement().getNodeName().toString();
if (rootNode.equals("Results"))
{
String Question = "";
String Answer = "";
String AverageRating = "";
float rating = 0;
String keyword = "";
NodeList nList = document.getElementsByTagName("Result");
for (int i = 0; i < nList.getLength(); i++)
{
Node nodes = nList.item(i);
if (nodes.getNodeType() == Node.ELEMENT_NODE)
{
Element element = (Element) nodes;
NodeList list = document.getElementsByTagName("Questions");
for (int value = 0; value < list.getLength(); value++)
{
Node node = list.item(value);
if (node.getNodeType() == Node.ELEMENT_NODE)
{
Element eElement = (Element) node;
Question = getValue("Question", eElement);
Answer = getValue("Answer", eElement);
AverageRating = getValue("AverageRating", eElement);
rating = Float.parseFloat(AverageRating);
}
}
}
NodeList keywordNode = document.getElementsByTagName("Keywords");
String keywords = "";
for (int y = 0; y < keywordNode.getLength(); y++)
{
Node node = keywordNode.item(y);
if (node.getNodeType() == Node.ELEMENT_NODE)
{
Element element = (Element) node;
NodeList ModList = document.getElementsByTagName("Keyword");
int count = ModList.getLength();
for (int b = 0; b < count; b++)
{
keyword = element.getElementsByTagName("Keyword").item(b).getTextContent();
keywords = keywords + keyword + "\n";
}
}
items.add(new Question(Question, Answer, rating, keywords));
}
}
}
}
catch (Exception e)
{
String s = e.getMessage();
publishProgress(s);
}
What I'm trying to achieve is for each question of each respective results in the Result tag of my XML, I want to get the question (and it's details) and the respective keywords, adding each to the Question class, then repeat for the next result from Results tag. Can someone please help with my code and show me where I'm going wrong?
Try importing these:
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
by downloading them at this site: http://www.xmlpull.org/
Then, try a code structure like this:
String XMLin;
XmlPullParserFactory factory;
String tag;
ArrayList<Question> questions = new ArrayList<Question>();
try {
XMLin = readString(instream);
} catch (IOException e1) {
// TODO Auto-generated catch block
XMLin = "Something went wrong";
}
try {
// Set up the Class that will be parsing the xml file
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader (XMLin));
// Get the first event type
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
// While we have not reached the end of the document, check for start tags
if (eventType == XmlPullParser.START_TAG) {
tag = xpp.getName();
if (tag.equals("Questions") && eventType == XmlPullParser.START_TAG) {
Question question = new Question();
do {
if (tag.equals("Question")) {
// Add question text to question
eventType = xpp.next();
String text = xpp.getText(); // Text between tags
} else if (tag.equals("Answer")) {
eventType = xpp.next();
String text = xpp.getText(); // Text between tags
} else if (tag.equals("AvergaeRating") {
eventType = xpp.next();
String text = xpp.getText(); // Text between tags
}
eventType = xpp.next();
if (eventType == XmlPullParser.TEXT) {
tag = xpp.getText();
} else {
tag = xpp.getName();
}
} while (!tag.equals("Questions"))
questions.add(question);
}
}
}
This is a modified example of something I used to parse through XML. Essentially, check for the tag name and event (whether it's a start tag or end tag, etc) and then perform that actions you want depending on those two values, such as add the text inbetween into a Question object or whatnot.
I managed to use this code:
try
{
//Creates the document
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(serverResult)));
//optional, but recommended
//read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
document.getDocumentElement().normalize();
//Look at root node's type (e.g. <query> or <login> or <add>)
String rootNode = document.getDocumentElement().getNodeName().toString();
if (rootNode.equals("Results"))
{
//Any methods which need to be called that will be used to query the database
//Always sending the String XML through as a parameter
//Look at the child node
String Question = "";
String Answer = "";
String AverageRating = "";
float rating = 0;
String keywords = "";
NodeList nList = document.getElementsByTagName("Questions");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++)
{
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE)
{
Element eElement = (Element) nNode;
Question = getValue("Question", eElement);
Answer = getValue("Answer", eElement);
AverageRating = getValue("AverageRating", eElement);
rating = Float.parseFloat(AverageRating);
NodeList List = document.getElementsByTagName("Keywords");
for (int a = 0; a < List.getLength(); a++)
{
Node node = List.item(temp);
if (node.getNodeType() == Node.ELEMENT_NODE)
{
Element element = (Element) node;
String Keyword = element.getElementsByTagName("Keyword").item(0).getTextContent();
keywords = keywords + Keyword + "\n";
}
}
}
items.add(new Question(Question, Answer, rating, keywords));
}
}
}
catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
which then get's each individual question (and all their information - question, answer, rating) and well as the respective keywords for that question and add to a Question object, then loop back. I wasn't putting the keywords XML parse within the questions for loop. Hopefully this helps someone who is struggling with similar problems.
I'm using DOM Parser to parse this XML feed: http://loc.grupolusofona.pt/index.php/?format=feed
I got the Parser working fine for all tags, i'm just missing ideas to be able to retrieve the image from within the description tag.
The description tag on the feed looks like this:
<description><![CDATA[<div class="K2FeedIntroText"><p><img style="margin: 10px;"
alt="joana soares rostos" src="http://loc.grupolusofona.pt/images/stories/varios/joana%20soares%20rostos.jpg"
height="110" width="120" />Quis ser veterinária mas deixou-se seduzir pela magia
de retratar o real. Joana Soares frequenta o primeiro ano do curso de Fotografia
da Lusófona e descreve a sua paixão pelas fotos como «inexplicável».</p>
</div>]]></description>
And i wanted to retrieve the image link:
http://loc.grupolusofona.pt/images/stories/varios/joana%20soares%20rostos.jpg
My Parser :
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 ) {
if( elem != null){
return elem.getTextContent();
}
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));
}
}
And my Main Activity:
public class Noticias extends ListActivity {
// All static variables
static final String URL = "http://loc.grupolusofona.pt/index.php/?format=feed";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_DESC = "description";
static final String KEY_LINK = "link";
static final String KEY_PUBDATE = "pubDate";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_noticias);
ArrayList<HashMap<String, Spanned>> menuItems = new ArrayList<HashMap<String, Spanned>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting 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
HashMap<String, Spanned> map = new HashMap<String, Spanned>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_ID, Html.fromHtml(parser.getValue(e, KEY_ID)));
map.put(KEY_TITLE, Html.fromHtml(parser.getValue(e, KEY_TITLE)));
map.put(KEY_DESC, Html.fromHtml(parser.getValue(e, KEY_DESC)));
map.put(KEY_PUBDATE, Html.fromHtml(parser.getValue(e, KEY_PUBDATE)));
map.put(KEY_LINK, Html.fromHtml(parser.getValue(e, KEY_LINK)));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.linha_feed,
new String[] { KEY_TITLE, KEY_DESC, KEY_PUBDATE, KEY_LINK }, new int[] {
R.id.title, R.id.desc, R.id.pub, R.id.link});
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String title = ((TextView) view.findViewById(R.id.title)).getText().toString();
String description = ((TextView) view.findViewById(R.id.desc)).getText().toString();
String pub = ((TextView) view.findViewById(R.id.pub)).getText().toString();
String link = ((TextView) view.findViewById(R.id.link)).getText().toString();
// Starting new intent
System.out.println("Title: " + title);
System.out.println("Link: " + link);
System.out.println("Description:" + description);
System.out.println("Pubdate: " + pub);
Intent in = new Intent(Intent.ACTION_VIEW);
in.setData(Uri.parse(link));
startActivity(in);
}
});
}
}
Any ideas ?
Thanks for your time.
Use RegEx with a simple pattern like this:
<\s*img\s*[^>]+src\s*=\s*(['"]?)(.*?)\1
Here use these functions:
public static String getMatch(String patternString, String text, int groupIndex){
Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE | Pattern.DOTALL );
return RegEx.getMatch(pattern, text, groupIndex);
}
public static String getMatch(Pattern pattern, String text, int groupIndex){
if(text!=null){
Matcher matcher = pattern.matcher(text);
String match = null;
while(matcher.find()){
match = matcher.group(groupIndex);
break;
}
return match;
}else{
return null;
}
}
Then you can plug in that pattern like this:
String imageSource = getMatch("<\\s*img\\s*[^>]+src\\s*=\\s*(['\"]?)(.*?)\\1", description, 2);
this is my xml structure :
<menu>
<item_category>
<category_name>ICECREAM</category_name>
<item>
<item_name>SOFTY</item_name>
<item_price>7.00</item_price>
</item>
<item>
<item_name>STICK</item_name>
<item_price>15.00</item_price>
</item>
<item>
<item_name>CONE</item_name>
<item_price>25.00</item_price>
</item>
</item_category>
<item_category>
<category_name>PIZZA</category_name>
<item>
<item_name>PIZZA-HOT</item_name>
<item_price>35.00</item_price>
</item>
<item>
<item_name>PIZZA-CRISPY</item_name>
<item_price>29.00</item_price>
</item>
</item_category>
</menu>
this is my code where i am parsing into list view
public class AndroidXMLParsingActivity extends ListActivity {
// All static variables
//static final String URL = "http://api.androidhive.info/pizza/?format=xml";
static final String URL = "http://192.168.1.112/dine/index.php/dineout/mob_view";
//static final String URL = "http://192.168.1.112/dineout/index.php/dineout/view";
// XML node keys
static final String KEY_MENU= "menu"; // parent node
//static final String KEY_ID = "foodjoint_id";
static final String KEY_CATEGORY= "category_name";
static final String KEY_ITEM= "item";
static final String KEY_ITEM_NAME= "item_name";
static final String KEY_PRICE= "item_price";
#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_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++)
{
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
map.put(KEY_CATEGORY, parser.getValue(e,KEY_CATEGORY));
map.put(KEY_ITEM_NAME, parser.getValue(e, KEY_ITEM_NAME));
map.put(KEY_PRICE, parser.getValue(e, KEY_PRICE));
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] {KEY_CATEGORY,KEY_ITEM_NAME,KEY_PRICE}, new int[] {R.id.category,R.id.name,R.id.costlab });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String category = ((TextView) view.findViewById(R.id.category)).getText().toString();
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
//String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
//in.putExtra(KEY_ITEM, name);
in.putExtra(KEY_CATEGORY, category);
in.putExtra(KEY_ITEM_NAME,name);
in.putExtra(KEY_PRICE, cost);
//in.putExtra(KEY_DESC, description);
startActivity(in);
}
});
}
}
My problem is i am not getting the value of category_name. I tried with nested loop but its all the same. please help me . what should i change in the code.
This is my xmlParser
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));
}
try this way
NodeList n,ncategories;
Element e;
static final String KEY_ITEMCATEGORY= "item_category";
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
ncategories = doc.getElementsByTagName(KEY_MENU);
for(int i=0;i<ncategories.getLength();i++){
e=(Element)ncategories.item(i);
n=e.getElementsByTagName(KEY_ITEMCATEGORY);
for(int c=0;c<n.getLength();c++){
HashMap<String, String> map = new HashMap<String, String>();
e=(Element)n.item(c);
String category= parser.getValue(e, KEY_CATEGORY).toString();
Log.e("catname", parser.getValue(e, KEY_CATEGORY).toString());
map.put(KEY_CATEGORY, category);
NodeList ns=e.getElementsByTagName(KEY_ITEM);
for(int j=0;j<ns.getLength();j++){
e=(Element)ns.item(j);
Log.e("itemname", parser.getValue(e,KEY_ITEM_NAME).toString());
Log.e("itemprice", parser.getValue(e, KEY_PRICE).toString()+"\n");
map.put(KEY_ITEM_NAME, parser.getValue(e, KEY_ITEM_NAME));
map.put(KEY_PRICE, parser.getValue(e, KEY_PRICE));
}
menuItems.add(map);
}
Try something like this:
NodeList nl_Cat = doc.getElementsByTagName(KEY_ITEM_CATEGORY);
for (int i = 0; i < nl_Cat.getLength(); i++)
{
HashMap<String, String> map = new HashMap<String, String>();
Element cat = (Element) nl_Cat(i);
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
for (int j = 0; j < nl.getLength(); j++)
{
Element e = (Element) nl.item(j);
map.put(KEY_ITEM_NAME, parser.getValue(e, KEY_ITEM_NAME));
map.put(KEY_PRICE, parser.getValue(e, KEY_PRICE));
}
menuItems.add(map);
}
Hope this works!
You are retrieving list of item elements and trying to find category_name in item element. However, looking at your xml, category_name is sibling of item element, not child. So you will not get category name in that way.
You might want to retrieve list of item_category and then populate items from it.
NodeList nl_categories = doc.getElementsByTagName(KEY_ITEM_CATEGORY);
for(int i = 0; i < nl_categories; i++)
{
Element e = (Element) nl.item(i);
String category = parser.getValue(e,KEY_CATEGORY);
NodeList nl = e.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int j = 0; j < nl.getLength(); j++)
{
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(j);
map.put(KEY_CATEGORY, category);
map.put(KEY_ITEM_NAME, parser.getValue(e, KEY_ITEM_NAME));
map.put(KEY_PRICE, parser.getValue(e, KEY_PRICE));
menuItems.add(map);
}
}