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 "";
}
}
Related
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.
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());
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 am consuming a web service as its output is an XML string. I am parsing it into a document and getting each child node value one by one and inserting into my SQLlite table as shown below:
public void DownloadAndInsertProblemAndReasonCode(String serverIPAddress,
String deviceId) {
String SOAP_ACTION = "http://VisionEPODWebService/GetProblemAndReasonCodesNew";
String OPERATION_NAME = "GetProblemAndReasonCodesNew";
String WSDL_TARGET_NAMESPACE = "http://VisionEPODWebService/";
String SOAP_ADDRESS = "";
SOAP_ADDRESS = "http://" + serverIPAddress
+ "/VisionEPODWebService/SystemData.asmx";
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,
OPERATION_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER10);
request.addProperty("deviceID", deviceId);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
try {
httpTransport.call(SOAP_ACTION, envelope);
Object response = envelope.getResponse();
DocumentBuilderFactory docBuilberFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docBuilberFactory.newDocumentBuilder();
InputSource inputSource = new InputSource();
inputSource
.setCharacterStream(new StringReader(response.toString()));
Document doc = docBuilder.parse(inputSource);
NodeList nodesProblemCode = doc
.getElementsByTagName("tblProblemCode");
ContentValues initialProblemCodeValues = new ContentValues();
dbAdapter = new DatabaseAdapter(this.context);
dbAdapter.open();
dbAdapter.BeginTransaction();
dbAdapter.DeleteRecord("tblProblemCode", "", "");
for (int i = 0; i < nodesProblemCode.getLength(); i++) {
Element element = (Element) nodesProblemCode.item(i);
NodeList PKProblemCode = element
.getElementsByTagName("PKProblemCode");
Element line = (Element) PKProblemCode.item(0);
initialProblemCodeValues.put("PKProblemCode",
getCharacterDataFromElement(line).toString());
NodeList ProblemCode = element
.getElementsByTagName("ProblemCode");
line = (Element) ProblemCode.item(0);
initialProblemCodeValues.put("ProblemCode",
getCharacterDataFromElement(line));
NodeList ProblemCodeDescription = element
.getElementsByTagName("ProblemCodeDescription");
line = (Element) ProblemCodeDescription.item(0);
initialProblemCodeValues.put("ProblemCodeDescription",
getCharacterDataFromElement(line).toString());
NodeList VWReturn = element.getElementsByTagName("VWReturn");
line = (Element) VWReturn.item(0);
initialProblemCodeValues.put("VWReturn",
getCharacterDataFromElement(line).toString());
dbAdapter.InsertRecord("tblProblemCode", "",
initialProblemCodeValues);
}
NodeList nodesReasonCode = doc
.getElementsByTagName("tblReasonCode");
ContentValues initialReasonCodeValues = new ContentValues();
dbAdapter.DeleteRecord("tblReasonCode", "", "");
for (int i = 0; i < nodesReasonCode.getLength(); i++) {
Element element = (Element) nodesReasonCode.item(i);
NodeList PKReasonCode = element
.getElementsByTagName("PKReasonCode");
Element line = (Element) PKReasonCode.item(0);
initialReasonCodeValues.put("PKReasonCode",
getCharacterDataFromElement(line).toString());
NodeList ReasonDescription = element
.getElementsByTagName("ReasonDescription");
line = (Element) ReasonDescription.item(0);
initialReasonCodeValues.put("ReasonDescription",
getCharacterDataFromElement(line));
dbAdapter.InsertRecord("tblReasonCode", "",
initialReasonCodeValues);
}
dbAdapter.SetSucessfulTransaction();
dbAdapter.EndTransaction();
dbAdapter.close();
}
catch (Exception exception) {
exception.toString();
}
}
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "?";
}
The problem is that after some time the XML string will not have some of child node. For example
"ProblemCode" child node.....at that time the code shows error.
How can I check whether there exists an element in the document, or whether values exist or not for the element?
I think you need to check if the child node exists: specifically for your problem node:
NodeList NL = element.getElementsByTagName("PKProblemCode");
if ((NL==null)||(NL.getLength()==0)) {
//No such node so use a default instead
} else
Element line = (Element) PKProblemCode.item(0);
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());