How to parse XML by attribute values? - android

Introduction
I have a summarized "country.xml" file shown below that I got from a website
I need to parse this xml by its attribute names.
For example I want to have such a list:
Country: Germany
Population: 82521653
GDP: 3466000000000
Country: Switzerland
Population: 8417700
GDP: 659800000000
The problem is, that the tag names are almost the same.
What I've got now
Country: Germany
Population: Germany
GDP: Germany
Country: Switzerland
Population: Switzerland
GDP: Switzerland
Country: Austria
Population: Austria
GDP: Austria
MainActivity.java
public class MainActivity extends Activity {
TextView tv1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1=(TextView)findViewById(R.id.textView1);
try {
InputStream is = getAssets().open("country.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is);
Element element=doc.getDocumentElement();
element.normalize();
NodeList nList = doc.getElementsByTagName("Country");
for (int i=0; i<nList.getLength(); i++) {
Node node = nList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element2 = (Element) node;
tv1.setText(tv1.getText()+"\nCountry : " + getValue("string", element2)+"\n");
tv1.setText(tv1.getText()+"Population : " + getValue("string", element2)+"\n");
tv1.setText(tv1.getText()+"GDP : " + getValue("string", element2)+"\n");
tv1.setText(tv1.getText()+"-----------------------");
}
}
} catch (Exception e) {e.printStackTrace();}
}
private static String getValue(String tag, Element element) {
NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = nodeList.item(0);
return node.getNodeValue();
}
}
Country.xml
<Country>
<string name="CountryName">Germany</string>
<string name="Population">82521653</string>
<null name="Area">357385</null>
<null name="GDP">3466000000000</null>
</Country>
<Country>
<string name="CountryName">Switzerland</string>
<string name="Population">8417700</string>
<null name="Area">41285</null>
<null name="GDP">659800000000</null>
</Country>
<Country>
<string name="CountryName">Austria</string>
<string name="Population">8772865</string>
<null name="Area">83878</null>
<null name="GDP">386700000000</null>
</Country>
Question
How can I get the values by its attribute names?
What I tried is:
tv1.setText(tv1.getText()+"\nCountry : " + getValue("string name=\"CountryName\"", element2)+"\n");
But this gives me an empty string back.

I think, you can't get the textContent of an element by the attribute name directley.
But you can do it like this:
Call getValue for each country, as you did, but give it the correct tag names (like "CountryCode").
In getValue() you first get a list of the child nodes for the Country element.
Then you get the attribute name for each child node and compare it with the tag name. If its equal, you return the textContent of the element.
Have a look here, it works like this:
public class MainActivity extends Activity {
TextView tv1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1=(TextView)findViewById(R.id.textView1);
try {
InputStream is = getAssets().open("country.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is);
Element element=doc.getDocumentElement();
element.normalize();
NodeList nList = doc.getElementsByTagName("Country");
for (int i=0; i<nList.getLength(); i++) {
Node node = nList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element2 = (Element) node;
tv1.setText(tv1.getText()+"\nCountry : " + getValue("CountryName", element2)+"\n");
tv1.setText(tv1.getText()+"Population : " + getValue("Population", element2)+"\n");
tv1.setText(tv1.getText()+"GDP : " + getValue("GDP", element2)+"\n");
tv1.setText(tv1.getText()+"-----------------------");
}
}
} catch (Exception e) {e.printStackTrace();}
}
private static String getValue(String tag, Element element) {
NodeList childNodes = element.getChildNodes();
for (int i=0 ; i<childNodes.getLength() ; i++) {
if (childNodes.item(i).hasAttributes()) {
String attributeName = childNodes.item(i).getAttributes().item(0).getNodeValue();
if (attributeName.equals(tag)) {
return childNodes.item(i).getTextContent();
}
}
}
return null;
}
}

Related

what is use of getchildnodes in code given below in android?

Here is My xml document iam trying to prase it using DOMXmlParser..
< records>
<employee>
<name>Sachin Kumar</name>
<salary>50000</salary>
</employee>
<employee>
<name>Rahul Kumar</name>
<salary>60000</salary>
</employee>
<employee>
<name>John Mike</name>
<salary>70000</salary>
</employee>
< /records>
Following is Code in OnCreate.
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView) findViewById(R.id.textView1);
try {
InputStream is = getAssets().open("file.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is);
Element element = doc.getDocumentElement();
element.normalize();
NodeList nList = doc.getElementsByTagName("employee");
System.out.println("No Of Collected Objects" + nList.getLength() );
for (int i = 0; i < nList.getLength(); i++) {
Node node = nList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element2 = (Element) node;
tv1.setText(tv1.getText()+"\n\nFirstName : "
+ getValue("firstname",element2) + "\n");
tv1.setText(tv1.getText()+"\n\nMiddleName : "
+ getValue("middlename",element2) + "\n");
tv1.setText(tv1.getText()+"\n\nLastName : "
+ getValue("lastname",element2) + "\n");
tv1.setText(tv1.getText() + "Salary : "
+ getValue("salary",element2) + "\n");
tv1.setText(tv1.getText() + "-----------------------");
}
}
}
Can anyone tell what is the use of getChildNodes in following code and why the item index should always be 0 ??.
private static String getValue(String tag, Element element) {
NodeList nodeList = element.getElementsByTagName(tag).item(0)
.getChildNodes();
Node node = (Node) nodeList.item(0);
return node.getNodeValue();
}
getChildNotes retrieves a list of all child nodes of the first element with "tag".
Then node is assigned the first element in the returned list.

XML parsing for complex xml

Actually i try to do xml parsing from my local host and retrieve the value into the spinner.
what my doubt is i also need to retrieve the value inside the attribute which was present inside the book node (i,e) . I refer many tutorials and source codes still i cant able to do it. Any one please help to do it. Thanks in advance.
XML Structure
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>
An in-depth look at creating applications with XML.
</description>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>
A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.
</description>
</book>
<book id="bk103">
<author>Corets, Eva</author>
<title>Maeve Ascendant</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-11-17</publish_date>
<description>
After the collapse of a nanotechnology society in England, the young survivors lay the foundation for a new society.
</description>
</book>
<book id="bk104">
<author>Corets, Eva</author>
<title>Oberon's Legacy</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-03-10</publish_date>
<description>
In post-apocalypse England, the mysterious agent known only as Oberon helps to create a new life for the inhabitants of London. Sequel to Maeve Ascendant.
</description>
</book>
</catalog>
Java code
public class MainActivity extends Activity implements AdapterView.OnItemSelectedListener {
ArrayList<String> title;
Button button;
Spinner spinner;
ArrayAdapter<String> from_adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
title = new ArrayList<String>();
button = (Button) findViewById(R.id.button1);
spinner = (Spinner) findViewById(R.id.spinner1);
spinner.setOnItemSelectedListener(this);
button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
parse();
from_adapter=new ArrayAdapter<String>(getBaseContext(),android.R.layout.simple_spinner_item, title);
from_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(from_adapter);
}
});
}
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
Toast.makeText(parent.getContext(), ""+spinner.getSelectedItem().toString().trim(),
Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
protected void parse() {
// TODO Auto-generated method stub
try {
URL url = new URL(
"http://10.0.2.2/book.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("book");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element idElmnt = (Element) node;
NodeList idList = idElmnt.getElementsByTagName("id");
Element idElement = (Element) idList.item(0);
idList = idElement.getChildNodes();
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("author");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
NodeList websiteList = fstElmnt.getElementsByTagName("title");
Element websiteElement = (Element) websiteList.item(0);
websiteList = websiteElement.getChildNodes();
NodeList websiteList1 = fstElmnt.getElementsByTagName("genre");
Element websiteElement1 = (Element) websiteList1.item(0);
websiteList1 = websiteElement1.getChildNodes();
NodeList websiteList2 = fstElmnt.getElementsByTagName("price");
Element websiteElement2 = (Element) websiteList2.item(0);
websiteList2 = websiteElement2.getChildNodes();
title.add(((Node) idList.item(0)).getNodeValue()+":"+((Node) nameList.item(0)).getNodeValue()+":"+((Node) websiteList.item(0)).getNodeValue() +"\n"+((Node) websiteList1.item(0)).getNodeValue()+"-"+((Node) websiteList2.item(0)).getNodeValue());
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
}
try this code inside for loop.
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
String value=node.getNodeValue();// you can store this in array for all nodes
Element idElmnt = (Element) node;
NodeList idList = idElmnt.getElementsByTagName("id");
Element idElement = (Element) idList.item(0);
idList = idElement.getChildNodes();
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("author");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
NodeList websiteList = fstElmnt.getElementsByTagName("title");
Element websiteElement = (Element) websiteList.item(0);
websiteList = websiteElement.getChildNodes();
NodeList websiteList1 = fstElmnt.getElementsByTagName("genre");
Element websiteElement1 = (Element) websiteList1.item(0);
websiteList1 = websiteElement1.getChildNodes();
NodeList websiteList2 = fstElmnt.getElementsByTagName("price");
Element websiteElement2 = (Element) websiteList2.item(0);
websiteList2 = websiteElement2.getChildNodes();
title.add(((Node) idList.item(0)).getNodeValue()+":"+((Node) nameList.item(0)).getNodeValue()+":"+((Node) websiteList.item(0)).getNodeValue() +"\n"+((Node) websiteList1.item(0)).getNodeValue()+"-"+((Node) websiteList2.item(0)).getNodeValue());
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}

Android Parse xml with DOM - same named tags

I have an rss feed where, in every item tag there are two tags named category. I want to get the value of the first one,but unfortunately i get the second one value. This is my code:
// Create required instances
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
// Parse the xml
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
// Get all <item> tags.
NodeList nl = doc.getElementsByTagName("item");
int length = nl.getLength();
// to length einai posa nea tha emfanisei.Edw tou lew ola pou
// vriskei
for (int i = 0; i < length; i++) {
Node currentNode = nl.item(i);
RSSItem _item = new RSSItem();
NodeList nchild = currentNode.getChildNodes();
int clength = nchild.getLength();
// Get the required elements from each Item
for (int j = 0; j < clength; j = j + 1) {
Node thisNode = nchild.item(j);
String theString = null;
if (thisNode != null && thisNode.getFirstChild() != null) {
theString = thisNode.getFirstChild().getNodeValue();
}
if (theString != null) {
String nodeName = thisNode.getNodeName();
...
....
...
if ("category".equals(nodeName)) {
/*
* NodeList nlList = nl.item(0).getChildNodes();
* Node nValue2 = (Node) nlList.item(0);
* _item.setCategory(nValue2.getNodeValue());
*/
_item.setCategory(theString);
}
}
}
EDIT:
My RSS feed is like:
<item>
<title>my title</title>
<category>Sports</category>
<category>World</category>
</item>
<item>
<title>my title 2</title>
<category>News</category>
<category>Showbiz</category>
</item>
...etc
if you want to get first category from current item Nodes then use Element.getElementsByTagName("category") for getting all category nodes in NodeList and after that use NodeList.item(0) to get first category Element from NodeList do it as:
Element element = (Element) currentNode;
NodeList nodelist = element.getElementsByTagName("category");
Element element1 = (Element) nodelist.item(0);
NodeList category = element1.getChildNodes();
System.out.print("category : " + (category.item(0)).getNodeValue());

Getting content of a XML node by the attribute

I have a XML file like this:
<?xml version="1.0"?>
<settings>
<mail id="sender">
<host>content here</host>
<port>25</port>
<account>tmt#example.com</account>
<password>password</password>
</mail>
<mail id="receiver">
<account>tmt#example.com</account>
</mail>
<mail id="support">
<account>tmt#example.com</account>
</mail>
</settings>
How can I get the attribute of each element, parse the content of each element and save the content in SharedPreference
This is what I've done so far:
The Contructor:
public ReadConfig(Context context, ProgressBar progressBar) throws ParserConfigurationException, SAXException, IOException {
this.context = context;
this.progressBar = progressBar;
folders = new CreateApplicationFolder();
dbf = DocumentBuilderFactory.newInstance();
db = dbf.newDocumentBuilder();
doc = db.parse(new File(folders.getPathToNode() + "/settings_config.xml"));
doc.getDocumentElement().normalize();
}
And my doInBackground method
#Override
protected String doInBackground(String... params) {
Log.i("ROOT NODE: ", doc.getDocumentElement().getNodeName());
NodeList listOfMail = doc.getElementsByTagName("mail");
int totalMail = listOfMail.getLength();
Log.i("LENGTH: ", Integer.toString(totalMail));
for(int i = 0; i < totalMail; i++) {
Node firstMailSetting = listOfMail.item(i);
}
}
From the LogCat I know that there are three elements, which is correct.
import org.w3c.dom.Element;
for(int i = 0; i < totalMail; i++) {
Node firstMailSetting = listOfMail.item(i);
Element e = (Element) firstMailSetting ;
String acc = getTagValue("account", e); <-----
}
private String getTagValue(String sTag, Element eElement) {
try {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
}
catch (Exception e) {
return "";
}
}

Can't parse XML with DOM in android

I am having some trouble parsing XML in Android from an URL. I don't know if it's the XML parsing that's the problem or only when I am trying to show it on the screen because
setListAdapter(new ArrayAdapter<String>(ANDROIDXMLActivity.this, android.R.layout.simple_list_item_1, stopNumbers));
wont show anything. The code below works perfectly in a java program.
URL: http://maps.travelsouthyorkshire.com/iGNMSearchService.asmx/FindObjectsWithinExtent?xMin=435360&yMin=387260&xMax=435960&yMax=387860&zoomLevel=0
try {
ArrayList<Double> xCords = new ArrayList<Double>();
ArrayList<Double> yCords = new ArrayList<Double>();
ArrayList<String> stopNumbers = new ArrayList<String>();
ArrayList<String> bussLocations = new ArrayList<String>();
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder
.parse(new URL(
"http://maps.travelsouthyorkshire.com/iGNMSearchService.asmx/FindObjectsWithinExtent?xMin=435360&yMin=387260&xMax=435960&yMax=387860&zoomLevel=0")
.openStream());
// normalize text representation
doc.getDocumentElement().normalize();
NodeList listOfObjects = doc.getElementsByTagName("iGNMObject");
for (int s = 0; s < listOfObjects.getLength(); s++) {
Node firstPersonNode = listOfObjects.item(s);
if (firstPersonNode.getNodeType() == Node.ELEMENT_NODE) {
Element firstPersonElement = (Element) firstPersonNode;
NodeList stopNumList = firstPersonElement
.getElementsByTagName("StopNumber");
Element ageElement = (Element) stopNumList.item(0);
if (ageElement != null) {
NodeList textAgeList = ageElement.getChildNodes();
String stop = ((Node) textAgeList.item(0))
.getNodeValue().trim();
stopNumbers.add(stop);
// ------
// -------
NodeList xPosList = firstPersonElement
.getElementsByTagName("XPosition");
Element firstNameElement = (Element) xPosList.item(0);
NodeList textFNList = firstNameElement.getChildNodes();
String temp2 = ((Node) textFNList.item(0))
.getNodeValue().trim();
double x = Double.parseDouble(temp2);
xCords.add(x);
// -------
NodeList yPosList = firstPersonElement
.getElementsByTagName("YPosition");
Element lastNameElement = (Element) yPosList.item(0);
NodeList textLNList = lastNameElement.getChildNodes();
String temp3 = ((Node) textLNList.item(0))
.getNodeValue().trim();
double y = Double.parseDouble(temp3);
yCords.add(y);
// ----
NodeList stopAkaList = firstPersonElement
.getElementsByTagName("StopAka");
Element stopAka = (Element) stopAkaList.item(0);
NodeList textStopAKAList = stopAka.getChildNodes();
String plats = ((Node) textStopAKAList.item(0))
.getNodeValue().trim();
bussLocations.add(plats);
} else {
}
}// end of if clause
}// end of for loop with s var
setListAdapter(new ArrayAdapter<String>(ANDROIDXMLActivity.this,
android.R.layout.simple_list_item_1, stopNumbers));
} catch (Exception e) {
}
}
}
}
Solved it. I had forgot to add internet permission in the manifest.

Categories

Resources