Parsing a xml file in android - android

I have a xml file :
<root>
<book
name="Science1"
author="XYZ1">
</book>
<book
name="Science2"
author="XYZ2">
</book>
</root>
I want to get the value of name and author. Java code to parse the above :
Document doc = null;
try {
InputStream is = getResources().openRawResource(R.raw.xmldata);//newfile
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(new InputSource(is));
NodeList nl1 = doc.getElementsByTagName("book");
for (int i = 0; i < nl1.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl1.item(i);
// adding each child node to HashMap key => value
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_AUTHOR,parser.getValue(e, KEY_AUTHOR));
Log.d("Debug","Value + " + parser.getValue(e, KEY_NAME) + " " + parser.getValue(e, KEY_AUTHOR));
// adding HashList to ArrayList
menuItems.add(map);
}
}
catch(Exception e)
{
e.printStackTrace();
}
What I am missing here, as when I print the tag value, I don't get any value.
Please suggest / help how can I read this format ? If this format has any other dependency like schema / DTD to be provided, let me know, as I am totally unaware of the correct flow. Please suggest me some site as well where I can validate my xml file as well.

Bring the xml-File in this format:
<root>
<book name="Science1"
author="XYZ1"/>
<book name="Science2"
author="XYZ2" />
</root>
And than for your for-loop:
for (int temp = 0; temp < nl1.getLength(); temp++) {
HashMap<String, String> map = new HashMap<String, String>();
Node nNode = nl1.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
map.put(KEY_NAME, eElement.getAttribute("name"));
map.put(KEY_AUTHOR, eElement.getAttribute("author"));
menuItems.add(map);
}
}
Hope it helps

Man, just read this tutorial:
http://developer.android.com/training/basics/network-ops/xml.html

Related

Get values from a XML contained in a String

I have a String variable containing an XML:
String xml = "<?xml version="1.0" encoding="utf-8" standalone="yes"?><CourtactSioux><ListeContact><IdContactClient>212</IdContactClient><DateContact>25/06/2012 08:09</DateContact><TypeForm>STANDARD</TypeForm><Foyer>2</Foyer><Civilite>M</Civilite><Nom>TEST</Nom><Prenom>JULIEN</Prenom><NomJeuneFille></NomJeuneFille></ListeContact></CourtactSioux>"
And I want to take values from this XML, how to do ?
For exemple: get "Civilite" value.
I tried this:
String xml = cn.getXml();
Integer demandeId = cn.getID();
XMLParser parser = new XMLParser();
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++) {
Element e = (Element) nl.item(i);
idApplication = parser.getValue(e, IdApplication);
idContactClient = parser.getValue(e, IdContactClient);
logement = parser.getValue(e, Logement);
typeForm = parser.getValue(e, TypeForm);
}
id = idApplication + idContactClient;
Product product = new Product()
.setId(id)
.setName(logement)
.setCategory(typeForm)
.setPrice(1)
.setQuantity(1);
ProductAction productAction = new ProductAction(ProductAction.ACTION_PURCHASE)
.setTransactionId(id)
.setTransactionAffiliation("Solutis")
.setTransactionRevenue(1);
HitBuilders.ScreenViewBuilder builder = new HitBuilders.ScreenViewBuilder()
.addProduct(product)
.setProductAction(productAction);
Tracker t = ((App) getApplication()).getTracker();
t.setScreenName("transaction");
t.send(builder.build());
}
It's work, get attention on the aprent node of your xml
There are several ways of parsing XML in android. You could use XMLReader.parse(InputSource) by wrapping the string in a reader, as shown here
Check the Parsing XML Data part of Android Developers site for more information.

Parse two elements with same name android

I'm a bit new to XML and Android development... I've encountered this issue where I need to parse an XML where the elements are the same and include that with the overall element. It's a bit hard to explain, see code below:
<tns:camera>
<tns:congestionLocations>
<tns:congestion>Free Flow</tns:congestion>
<tns:direction>Eastbound</tns:direction>
</tns:congestionLocations>
<tns:congestionLocations>
<tns:congestion>Free Flow</tns:congestion>
<tns:direction>Westbound</tns:direction>
</tns:congestionLocations>
<tns:description>Bond St looking east</tns:description>
<tns:direction>Eastbound</tns:direction>
<tns:group>SH16-North-Western</tns:group>
<tns:lat>-36.869</tns:lat>
<tns:lon>174.746</tns:lon>
<tns:name>SH16 1 Bond St</tns:name>
<tns:viewUrl>http://www.trafficnz.info/camera/view/130</tns:viewUrl>
</tns:camera>
Basically, I need to parse the overall element (tns:camera) and include the congestion locations (seperated from each other obviously), but within the same class as i will be using all of them in a listview...
How would I achieve this?
At present, I am using the Pull Parser, and parsing it into a class object
PullParser code:
case XmlPullParser.END_TAG:
if (tagname.equalsIgnoreCase(KEY_SITE)) {current Site
CameraSites.add(curCameraClass);
} else if (tagname.equalsIgnoreCase(KEY_DESCRIPTION)) {
curCameraClass.setDescription(curText);
}else if (tagname.equalsIgnoreCase(KEY_NAME)) {
curCameraClass.setName(curText);
}
break;
Kind Regards!
Try this..
NodeList nodeList = doc.getElementsByTagName("tns:camera");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("tns:group");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
System.out.println("tns:group : "+((Node) nameList.item(0)).getNodeValue());
Element fstElmnt1 = (Element) node;
NodeList nameList1 = fstElmnt1.getElementsByTagName("tns:viewUrl");
Element nameElement1 = (Element) nameList1.item(0);
nameList1 = nameElement1.getChildNodes();
System.out.println("tns:viewUrl : "+ ((Node) nameList1.item(0)).getNodeValue());
//same as use to all tns:description,tns:direction and tns:lat etc.,
if(node.getNodeType() == Node.ELEMENT_NODE)
{
Element e = (Element) node;
NodeList resultNodeList = e.getElementsByTagName("tns:congestionLocations");
int resultNodeListSize = resultNodeList.getLength();
for(int j = 0 ; j < resultNodeListSize ; j++ )
{
Node resultNode = resultNodeList.item(j);
if(resultNode.getNodeType() == Node.ELEMENT_NODE)
{
Element fstElmnt2 = (Element) resultNode;
NodeList nameList2 = fstElmnt2.getElementsByTagName("tns:congestion");
Element nameElement2 = (Element) nameList2.item(0);
nameList2 = nameElement2.getChildNodes();
Log.v("tns:congestion", ""+((Node) nameList2.item(0)).getNodeValue());
Element fstElmnt3 = (Element) resultNode;
NodeList nameList3 = fstElmnt3.getElementsByTagName("tns:direction");
Element nameElement3 = (Element) nameList3.item(0);
nameList3 = nameElement3.getChildNodes();
Log.v("tns:direction--", ""+((Node) nameList3.item(0)).getNodeValue());
}
}
}
}
You can you SAXParser to parse the xml. Hope the following links will be helpful:
developersite
basic tutorial

Android parse a very simple XML Array

This might sound dumb, but I just need the help with the logic,
I have this very simple XML array:
<plist version="1.0">
<array>
<string>Lisa Jackson</string>
<string>Elisabeth Hartmann</string>
<string>C. J. Sansom</string>
<string>Irmengard Gabler</string>
<string>Oliver Pötzsch</string>
<string>Ulla Illerhaus</string>
<string>Christopher J. Sansom</string>
<string>Nina Blazon</string>
<string>Nicholas Lessing</string>
<string>Johannes Steck</string>
<string>Peter Kaempfe</string>
<string>Dimeter Inkiow</string>
<string>Barbara Sher</string>
<string>Ulrike Hübschmann</string>
<string>Otfried Preußler</string>
<string>Ulla Illerhaus</string>
<string>Annette Kurth</string>
</array>
</plist>
but when I try to parse it this way:
static final String KEY_ITEM = "string";
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);
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_ITEM, parser.getValue(e, KEY_ITEM));
menuItems.add(map);
}
It displays the list based on the number of the given (17 list items) on the XML file, but it doesn't display any of the content, like 'Lisa Jackson', 'Elisabeth Hartmann', etc.
How can I resolve this?
element.getTextContent();
This will get the text value needed.
OR
for (int in = 0; in < numberOfChildren; in++) {
Node node = nl.item(in);
Log.d("skt",node.getNodeName() + " = " + node.getTextContent());
//node.getTextContent() has the text. Add it to map
}

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));
}
}
}
}
}
}

How to parse XML (especific structure) in Android?

I need to parse a specific part of an XML obtained from a http request but I do not know how to do it!
I have the following XML structure being returned:
<categorias type="array">
<categoria>
<nome>
Alimentação
</nome>
<idcategoria>
5
</idcategoria>
<subcategorias>
<subcategoria>
<nome>
Todos
</nome>
<id>
5
</id>
</subcategoria>
</subcategorias>
</categoria>
</categorias>
I need to parse the data inside the subcategorias
tag because with the code I have now, I get only the upper tags, like
nome and idcategoria from the root tag categoria.
I've created a NodeList inside the for loop but it return all the subcategoria tags in the Document. And I need to get only the ones inside a unique categoria tag.
Here's the code I have now:
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++) {
// 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_ID, parser.getValue(e, KEY_ID));
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
// adding HashList to ArrayList
menuItems.add(map);
}
Can someone help me on this!?
Thanks in advance!
Have a look at this official document of Android which describe XMLPullParser.
You have to implement your logic according to your XML structure.
Aside from XMLPullParser, another option for parsing XML is to use the Simple XML library. It will allow you to easily deserialize that XML into an object which you can manipulate however you wish. It would be possible for you to ignore all other child elements in categoria and just capture subcategorias by using loose object mapping. Check the Simple Framework documentation for more information.
#Android Coader is right, "You have to implement your logic according to your XML structure"
Why do you have a KEY_ITEM, when there are no "item" tags in your XML? You need to specify in the code which tags you want to retrieve. For example, if you define a KEY_SUBCATEGORIA = "subcategoria", then to get all subcategory nodes you can do
NodeList nl = doc.getElementsByTagName(KEY_SUBCATEGORIA);
Then you should navigate through each node, pulling out the name and id's as you are doing now.
I got it!
I used only the same kind of structure I had before!
I added this code inside the for loop I had:
NodeList nlSubcategorias = e.getElementsByTagName("subcategoria");
ArrayList<HashMap<String, String>> subcategorias = new ArrayList<HashMap<String, String>>();
for (int j = 0; j < nlSubcategorias.getLength(); j++) {
HashMap<String, String> mapSub = new HashMap<String, String>();
Element eSub = (Element)nlSubcategorias.item(j);
mapSub.put(KEY_ID_SUB, parser.getValue(eSub, KEY_ID_SUB));
mapSub.put(KEY_NAME_SUB, parser.getValue(eSub, KEY_NAME_SUB));
subcategorias.add(mapSub);
System.out.println("subcategorias: " + subcategorias.get(j).get(KEY_NAME_SUB));
}
subcategoriasItems.add(subcategorias);

Categories

Resources