XML stands for Extensible Mark-up Language.XML is a very popular format and commonly used for sharing data on the internet.
Android provides three types of XML parsers
1)DOM.
2)SAX.
3)XMLPullParser.
XMLPullParser.
Click Here to get full code
output:
Android provides three types of XML parsers
1)DOM.
2)SAX.
3)XMLPullParser.
XMLPullParser.
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser parser = factory.newPullParser();
parser.setInput(is, null);
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
String tagname = parser.getName();
switch (eventType) {
case XmlPullParser.START_TAG:
if (tagname.equalsIgnoreCase("item")) {
// create a new instance of employee
_xmlmodel = new XmlModel();
}
break;
case XmlPullParser.TEXT:
text = parser.getText();
break;
case XmlPullParser.END_TAG:
if (tagname.equalsIgnoreCase("item")) {
// add employee object to list
_xmlmodel_response.add(_xmlmodel);
}else if (tagname.equalsIgnoreCase("id")) {
_xmlmodel.setId(text);
} else if (tagname.equalsIgnoreCase("name")) {
_xmlmodel.setName(text);
} else if (tagname.equalsIgnoreCase("cost")) {
_xmlmodel.setCost(text);
}else if (tagname.equalsIgnoreCase("description")) {
_xmlmodel.setDescription(text);
}
break;
default:
break;
}
eventType = parser.next();
}
SAX.
XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser()
.getXMLReader();
// create a SAXXMLHandler
SAXXMLHandler saxHandler = new SAXXMLHandler();
// store handler in XMLReader
xmlReader.setContentHandler(saxHandler);
// the process starts
xmlReader.parse(new InputSource(is));
// get the `Employee list`
employees = saxHandler.getEmployees();
DOM Handler
public Document getDocument(InputStream inputStream) {
Document document = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = factory.newDocumentBuilder();
InputSource inputSource = new InputSource(inputStream);
document = db.parse(inputSource);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return document;
}
public String getValue(Element item, String name) {
NodeList nodes = item.getElementsByTagName(name);
return this.getTextNodeValue(nodes.item(0));
}
private final String getTextNodeValue(Node node) {
Node child;
if (node != null) {
if (node.hasChildNodes()) {
child = node.getFirstChild();
while(child != null) {
if (child.getNodeType() == Node.TEXT_NODE) {
return child.getNodeValue();
}
child = child.getNextSibling();
}
}
}
return "";
}
Click Here to get full code
output: