Easy way to get the node value of this example - android

I have a sample XML (Android platform) and I wanted to know the easiest and most efficient approach to get the node value of the node "e". Please help.
<a>
<b>
<c>
<e>data</e>
</c>
</b>
<b>
</b>
</a>

Use XPath.
See - http://developer.android.com/reference/javax/xml/xpath/package-summary.html
The XPath expression to grab the correct element would be:
/a/b/c/e
You could coalesce the resulting node into a String to get the textual value.

I think following code will help you to extract data of "e" node.
NodeList nodes = doc.getElementsByTagName("b");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList nodesimg = element.getElementsByTagName("e");
for (int j = 0; j < nodesimg.getLength(); j++) {
Element line = (Element) nodesimg.item(j);
String value=getCharacterDataFromElement(line);
}
}
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "?";
}

Implement Pull Parser, example is given here: http://icodesnip.com/snippet/java/android-pull-parser-sample
So by your case, you have to write the condition inside the start tag for "e".

Related

parse XML file to get <img> tag "src" attributes value

I am trying to build a app that display the feed of a given twitter account without using Twitter's Oauth, instead I converted the twitter account feed page to an xml format using Twitrss.me the image src is buried inside the img tag under the src attribute
<img xmlns="http://www.w3.org/1999/xhtml" width="250"
src="https://pbs.twimg.com/media/CmEqtEuUoAISIC3.jpg"
xml:base="http://twitrss.me/twitter_user_to_rss/?user=capcomfighters" />
I was able to get all the other tags text content but I have no idea how to access the tag attributes and get the value for specific attribute
also if there is a better way to do this than parsing xml please let me know
I am using this function to get the content of the tags
private void ProcessXml(Document data) {
if (data != null) {
feedItems=new ArrayList<>();
Element root = data.getDocumentElement();
Node channel = root.getChildNodes().item(1);
NodeList items = channel.getChildNodes();
for (int i = 0; i < items.getLength(); i++) {
Node currentchild = items.item(i);
if (currentchild.getNodeName().equalsIgnoreCase("item")) {
FeedItem item=new FeedItem();
NodeList itemchilds = currentchild.getChildNodes();
for (int j = 0; j < itemchilds.getLength(); j++) {
Node current = itemchilds.item(j);
if (current.getNodeName().equalsIgnoreCase("title")){
item.setTitle(current.getTextContent());
item.setDescription(current.getTextContent());
}else if (current.getNodeName().equalsIgnoreCase("description")){
// item.setDescription(current.getTextContent());
}else if (current.getNodeName().equalsIgnoreCase("pubDate")){
item.setPubDate(current.getTextContent());
}else if (current.getNodeName().equalsIgnoreCase("img")){
item.setThumbnailUrl(current.getAttributes().getNamedItem("src").getNodeValue());
Log.d("PIC", "ProcessXml: "+current.getAttributes().getNamedItem("src").getNodeValue());
}
}
feedItems.add(item);
}
}
}
}

Parse XML data from url using DOM Parser

I want to parse xml file from url :
http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=cher&api_key=5d6ce941674603e4bb75cfad6cfa13b7
I want to parse following tags of the file :
<artist>
<name>Cher</name>
<image size="medium">http://userserve-ak.last.fm/serve/64/62286415.png</image>
</artist>
But i don't know how to get the value of these two tags only.
I have tried the example code from
http://www.androidhive.info/2011/11/android-xml-parsing-tutorial/
But it does not showing to parse same tag having different attribute value.
Can anyone guide me how this is done?
Thanx in advance.
from the link you provided, I have just extract a small part :
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName("artist");
// looping through all item nodes <artist>
for (int i = 0; i < nl.getLength(); i++) {
Element e = (Element) nl.item(i);
String name = parser.getValue(e, "name"));
String image = parser.getValue(e, "image"));
//if you want the artist 'Cher' sigh ;)
if (name.equals("Cher")){
//do whatever you want
}
}
Thankx. I solved my problem from this url :
Getting element using attribute
if(str.equals("image"))
{
n = item.getElementsByTagName(str);
for (int i = 0; i < n.getLength(); i++) {
Node subNode = n.item(i);
if (subNode.hasAttributes()) {
NamedNodeMap nnm = subNode.getAttributes();
for (int j = 0; j < nnm.getLength(); j++) {
Node attrNode = nnm.item(j);
if (attrNode.getNodeType() == Node.ATTRIBUTE_NODE) {
Attr attribute = (Attr) attrNode;
if( attribute.getValue().equals("medium"))
{
return this.getElementValue(n.item(i));
}
}
}
}
}
}

Problem in parsing nested tags in xml

I have an xml that i am parsing through DOM parser. the xml is of somewhat this sequence
<root>
<item1> abc </item1>
<item2> def </item2>
<item3> ghi </item3>
<item4>
<subItem4>
<name> xyz </name>
<id> 1 </id>
</subItem4>
<subItem4>
<name> asd </name>
<id> 2 </id>
</subItem4>
</item4>
</root>
According to this dummy xml i am reaching till subItem 4 but not to the childern of it. what i am trying is as follows to get innermost Items is:
NodeList slide = theElement.getElementsByTagName("item4").item(0).getChildNodes();
for(int i = 0; i<slide.getLength(); i++)
{
NodeList subSlides = theElement.getElementsByTagName("subItem4").item(0).getChildNodes();
for (int j=0; j<subSlides.getLength(); j++)
{
String subSlide_title = subSlides.item(i).getFirstChild().getNodeValue();
}
}
its not working. please can someone identify where am i doing the mistake in parsing. Any help is appreciated.
You are not using valid XML - you can't have spaces in tag names.
XML Names cannot contain white space, see here for valid values.
Update (following comment that the posted sample is representative of the actual XML):
Your access via the indexer of the node list is incorrect:
String subSlide_title = subSlides.item(i).getFirstChild().getNodeValue();
Try this instead (using j instead of i, as the inner loop variable is called):
String subSlide_title = subSlides.item(j).getFirstChild().getNodeValue();
NodeList nodes = doc.getElementsByTagName("item");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList nodesimg = element.getElementsByTagName("name");
for (int j = 0; j < nodesimg.getLength(); j++) {
Element line = (Element) nodesimg.item(j);
String value=getCharacterDataFromElement(line);
}
}
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "?";
}
I think above code will help you in parsing xml file.
The XML elements are all messed up.
There are literally 2 lines that don't have mistakes in them.
For instance
<subItem 4>
is syntactically wrong and I don't see what logical sense you could make out of it.
Do you mean
<subItem4>
as in the fourth sub item or
<subItem someAttribute="4">
I'd recommend learning XML, it's very simple... http://www.w3schools.com/xml/default.asp

Get Elements by Tag Name from a Node in Android (XML) Document?

I have an XML like this:
<!--...-->
<Cell X="4" Y="2" CellType="Magnet">
<Direction>180</Direction>
<SwitchOn>true</SwitchOn>
<Color>-65536</Color>
</Cell>
<!--...-->
There're many Cell elements, and I can get the Cell Nodes by GetElementsByTagName. However, I realise that Node class DOESN'T have GetElementsByTagName method! How can I get Direction node from that cell node, without go throught the list of ChildNodes? Can I get the NodeList by Tag name like from Document class?
Thank you.
You can cast the NodeList item again with Element and then use getElementsByTagName(); from Element class.
The best approach is to make a Cell Object in your project alongwith fields like Direction, Switch, Color. Then get your data something like this.
String direction [];
NodeList cell = document.getElementsByTagName("Cell");
int length = cell.getLength();
direction = new String [length];
for (int i = 0; i < length; i++)
{
Element element = (Element) cell.item(i);
NodeList direction = element.getElementsByTagName("Direction");
Element line = (Element) direction.item(0);
direction [i] = getCharacterDataFromElement(line);
// remaining elements e.g Switch , Color if needed
}
Where your getCharacterDataFromElement() will be as follow.
public static String getCharacterDataFromElement(Element e)
{
Node child = e.getFirstChild();
if (child instanceof CharacterData)
{
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}

Dom parsing in Android

If I parse the tag that contains <p>Some Text</p> tag, I get a null pointer exception.
My RSS feed is as follows:
<quaddeals_conditions><p>Limit one QuadDeal</p></quaddeals_conditions>
My code is:
if (name.equalsIgnoreCase("quaddeals_conditions")) {
property.normalize();
conditions = property.getFirstChild().getNodeValue();
}
You have an element inside an element .
Therefore retrieve all quaddeals and then iterate each one and retrieve from it the p element:
DocumentBuilder builder = factory.newDocumentBuilder();
Document dom = builder.parse(this.inputStream);
Element root = dom.getDocumentElement();
// snip
NodeList items = root.getElementsByTagName("quaddeals_conditions");
for (int i = 0; i < items.getLength(); i++) {
Node item = items.item(i);
NodeList properties = item.getChildNodes();
for (int j = 0; j < properties.getLength(); j++) {
Node property = properties.item(j);
String name = property.getNodeName();
if (name.equalsIgnoreCase("p")) {
property.getFirstChild().getNodeValue(); // Your paragraph data
}
}
}
Hope this helps.
is "name" not NULL? I dont see you check for that.
It's good coding practice to compare the other way if possible:
if ("quaddeals_conditions".equalsIgnoreCase(name))...
So even if "name" is NULL, you don't get a NullPointerException.
Always check for not null before accessing some object member.

Categories

Resources