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.
Related
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;
}
}
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());
Here is my code. I want to see these parsed strings into ListView in Android. How can I do this?
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlRecords));
Document doc = db.parse(is);
NodeList nodes = doc.getElementsByTagName("employee");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList name = element.getElementsByTagName("name");
Element line = (Element) name.item(0);
System.out.println("Name: " + getCharacterDataFromElement(line));
NodeList title = element.getElementsByTagName("title");
line = (Element) title.item(0);
System.out.println("Title: " + 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 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.
i have parsed xml using dom parser,but when the xml element contains no value it throws null pointer Exception.how to check this?...
here my code
NodeList TrackName1 = fstElmnt2.getElementsByTagName("Artist_Name");
Element TrackElement1 = (Element) TrackName1.item(0);
TrackName1 = TrackElement1.getChildNodes();
result=result+((Node) TrackName1.item(0)).getNodeValue()
String Artistname=((Node)TrackName1.item(0)).getNodeValue();
}
Just check for null before you try to use the value?
Object value = ((Node) TrackName1.item(0)).getNodeValue();
if (value != null) {
result = result + value;
}
NodeList nodeList = doc.getElementsByTagName("item");
description = new TextView[nodeList.getLength()];
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
description[i] = new TextView(this);
Element fstElmnt = (Element) node;
NodeList dataList = fstElmnt.getElementsByTagName("description");
Element dataElement = (Element) dataList.item(0);
dataList = dataElement.getChildNodes();
description[i].setText( ((Node) dataList.item(0)).getNodeValue());