xml parsing in android example
In your project create a class file and name it as XMLParser.java. The parser class mainly deals the following operations
XMLParser.java
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.StringReader; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; public class XMLParser { public final static Document XMLfromString(String xml) { Document doc = null; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); try { DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(new ByteArrayInputStream( xml.getBytes("UTF-8"))); //is.setCharacterStream(new StringReader(xml)); doc = db.parse(is); } catch (ParserConfigurationException e) { System.out.println("XML parse error: " + e.getMessage()); return null; } catch (SAXException e) { System.out.println("Wrong XML file structure: " + e.getMessage()); return null; } catch (IOException e) { System.out.println("I/O exeption: " + e.getMessage()); return null; } return doc; } /** * Returns element value * * @param elem * element (it is XML tag) * @return Element value otherwise empty String */ public final static String getElementValue(Node elem) { Node kid; String str = ""; if (elem != null) { if (elem.hasChildNodes()) { for (kid = elem.getFirstChild(); kid != null; kid = kid .getNextSibling()) { if (kid.getNodeType() == Node.TEXT_NODE) { // Log.d("XMLFUNCTIONS", kid.getNodeValue()); str = str + kid.getNodeValue(); } } } } return str; } public static int numResults(Document doc) { Node results = doc.getDocumentElement(); int res = -1; try { res = Integer.valueOf(results.getAttributes().getNamedItem("count") .getNodeValue()); } catch (Exception e) { res = -1; } return res; } public static String getValue(Element item, String str) { NodeList n = item.getElementsByTagName(str); return XMLfunctions.getElementValue(n.item(0)); } }
User XMPParser.java class
Document doc = XMLfunctions.XMLfromString(result); // Parent node is USER NodeList nodes = doc.getElementsByTagName("USER"); // fill in the list items from the XML document for (int i = 0; i < nodes.getLength(); i++) { Element e = (Element) nodes.item(i); mylist.add(XMLfunctions.getValue(e, "fname"));// mylist.add(XMLfunctions.getValue(e, "lname"));// }
0 comments:
Post a Comment