Thanks for reading!
Using XML parsing tutorial from here as a reference, I am trying to parse a simple XML RSS feed with the following structure.
Everything works fine and all values are parsed except for the following case: I am not able to get the content of the <img>
tag.
<feed>
<title>This is Title</title>
<count>10</count>
<desc>
This is a description for a sample feed <img src="http://someimagelink.com/img.jpg" />
</desc>
<link>This is link</link>
</feed>
This is what the endElement()
method looks like:
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if(localName.equals("feed")) {
//Add Records object to ArrayList
//Feed is a POJO class to store all the feed content.
//FeedList is an ArrayList to store multiple Feed objects.
mFeedList.add(mFeed);
}
else if(localName.equals("title")) {
mFeed.setTitle(currentValue.toString());
}
else if(localName.equals("count")) {
mFeed.setCount(currentValue.toString());
}
else if(localName.equals("desc")) {
mFeed.setDesc(currentValue.toString());
}
else if(localName.equals("img")) {
//NEVER hits here :(
mFeed.setImageUrl(currentValue.toString());
}
else if(localName.equals("link")) {
//BUT, hits here
mFeed.setLink(currentValue.toString());
}
Since <img>
tag is part of <desc>
tag, the code in last else if
condition never gets executed.
Note: When I read the the <desc>
tag, I could do a manual String
search to retrieve the <img>
tag content. But, I am sure there has to be a more efficient way.
Can someone guide me on to get content of the <img>
tag?
Thanks!
EDIT: Updated the <img>
tag. It is now closed correctly.
EDIT2: Updating with startElement()
code here. Also updated Feed XML and startElement()
code.
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if(localName.equals("feed")) {
//Instantiate Feed object
mFeed = new Feed();
}
else if(localName.equals("title")) {
currentValue = new StringBuffer("");
isBuffering = true;
}
else if(localName.equals("count")) {
currentValue = new StringBuffer("");
isBuffering = true;
}
else if(localName.equals("desc")) {
currentValue = new StringBuffer("");
isBuffering = true;
}
else if(localName.equals("img")) {
currentValue = new StringBuffer("");
isBuffering = true;
}
}
else if(localName.equals("link")) {
currentValue = new StringBuffer("");
isBuffering = true;
}
}
The
<img>
tag actually has no character content, and the value you're after has to be pulled out of the attributes.To do this, you need to override
startElement(String namespaceURI, String localName, String qName, Attributes atts)
, recognize the<img>
tag more or less as you're doing, and get the value you need out of theatts
parameter.Debugging help:
Using this (simple/stupid) handler:
This indicates that the
<img>
tag does indeed generate start and end events.