Wednesday, 4 September 2013

XML Parsing In Android

Introduction :-
There are two kinds of parsing in android
1) DOM Parsing
2) SAX Parsing
I used Dom parser in my android project because a DOM parser is rich in functionality. It creates a DOM tree in memory and allows you to access any part of the document repeatedly and allows you to modify the DOM tree.
Building the Sample
My xml format is:-
 <item>  
 <question id="1" >  
 <name>Question 1</name>  
 <option id="341">  
 <name>option 1</name>  
 </option>  
 <option id="342" >  
 <name>option 2</name>  
 </option>  
 </question>  
 </item>  

1) name the above xml as  “xml.xml”. 2) save this in raw folder.

Running the Sample

1) First of all initialize array list for saving the node items.

2) Then Initialize InputStream is a readable source of bytes.

3) Initialize Document Builder that defines the API to obtain DOM Document instances from an XML document. Using this class, an application programmer can obtain a document from XML.

4) Initialize document, The Document interface represents the entire  XML document. Conceptually, it is the root of the document tree, and provides the primary access to the document’s data.

5) Initialize node list with the tag name which u want to retrieve. The NodeList interface provides the abstraction of an ordered collection of nodes. Java code for parsing XML :- 



 ArrayList<String> childItems = new ArrayList<String>();  
 InputStream is = getResources().openRawResource(R.raw.xml);  
 DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();  
 Document doc = builder.parse(is, null);  
 doc.getDocumentElement().normalize();  
 NodeList nodeListQuestion = doc.getElementsByTagName("question");  
 After that we have to use loop for repeated search of nodes. At last we get all the items in one array list then we can use them when we needed.  
 for (int i = 0; i < nodeListQuestion.getLength(); i++) {  
 Node node = nodeListQuestion.item(i);  
 Element fstElmnt = (Element) node; NodeList nameList = fstElmnt.getElementsByTagName("name");  
 Element nameElement = (Element) nameList.item(0);  
 nameList = nameElement.getChildNodes();  
 items.add(((Node) nameList.item(0)).getNodeValue().toString());  
 if (node.getChildNodes().getLength() >= 1) {  
 NodeList listChilds = node.getChildNodes();  
 for (int j = 0; j < node.getChildNodes().getLength(); j++) {               Node child = listChilds.item(j);  
 Element fstElmnt1 = (Element) node;  
 NodeList nameList1 = fstElmnt1.getElementsByTagName("option");  
 Element nameElement1 = (Element) nameList1.item(0);  
 if (child.getNodeType() == Node.ELEMENT_NODE) {  
 if (child.getNodeName().equals("option")) {  
 String childName = child.getNodeName();  
 String childValue = ((Element) child).getTextContent();  
 childItems.add(childValue);  
 }  
 }  
 }  
 }  
 }  

Hope this post helps someone… :)


Happy Coding

No comments:

Post a Comment