Updated 15 December 2016
Extensible Markup Language (XML) is a set of rules for encoding documents in machine-readable form. XML is a popular format for sharing data on the internet. In android, you can get XML in response from a website and then you have to traverse the XML in order to get required data. XML can be parsed by many ways forexample XML pull parser and SAX parser, DOM parser etc.
SAX and pull parser are event based approach while DOM parser is object based approach. But Sax is used when we want to paese the whole XML.
SAX Parser:
Firstly you shuld have a xml in form of a string. If you dont then you can create so using StringWriter class and TransformerFactory class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
StringWriter sw = new StringWriter(); Transformer serializer = null; try { serializer = TransformerFactory.newInstance().newTransformer(); } catch (TransformerConfigurationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { serializer.transform(new DOMSource(YOUR ELEMENT), new StreamResult(sw)); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } String XML_string = sw.toString(); |
You have to mention the node element( org.w3c.dom.Element) which you want to convert in string and the above code will give you the string including node element.
So now you have your XML in form of a string named XML_string. Thus you can parse the xml as you need using Xml document builder and convert it into DOM document so that traversing can be done to find the required information (tags) .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
DocumentBuilder builder = null; try { builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch (Exception e) { e.printStackTrace();} doc = null; try { InputSource is = new InputSource(new StringReader(XML_string)); doc = builder.parse(is); } catch (Exception e) { e.printStackTrace(); } NodeList FirstNode = doc.getElementsByTagName(NODE_YOU_WANT); if(FirstNode.getLength()>0) { Element my_element = (Element) FirstNode.item(0); String Required_Data=my_element.getTextContent(); } |
The string Required_Data will contain the required value of that node. If there are more than one tag with the same name then loop can be applied to get all the values or the required tag values in a List.
1 2 3 4 5 6 7 8 |
List<string> allValues= new ArrayList<>(); NodeList node = doc.getElementsByTagName(YOUR_NODE); if (node.getLength() > 0) { for (int i = 0; i < node.getLength(); ++i) { Element node_ele = (Element) node.item(i); String value= node_ele.getTextContent(); allValues.add(value); }} |
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.