lets take a simple xml file ,, suppose we are getting any xml from server side (mean through url)... in the bellow given format
<root>
<item>
<name>sweet</name>
<type category="chocolate">Truffels...</type >
</item>
<item>
<name>dessert</name>
<type category="icecream">crunchy choco</type >
</item>
</root>
A simple xml file.
Lets Start:
We are going to parse it through DOM.
private void domHandler()
{
URL url = new URL("Your file path on server");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("item");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("name");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("name");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
String nameValue = ((Node) nameList.item(0)).getNodeValue();
NodeList typeList = fstElmnt.getElementsByTagName("type");
Element typeElement = (Element) typeList .item(0);
typeList = typeElement .getChildNodes();
String typeValue = ((Node) typeList .item(0)).getNodeValue());
String typeCategory = typeElement .getAttribute("category"));
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
}
}
NodeList typeList = fstElmnt.getElementsByTagName("type");
Element typeElement = (Element) typeList .item(0);
typeList = typeElement .getChildNodes();
String typeValue = ((Node) typeList .item(0)).getNodeValue());
String typeCategory = typeElement .getAttribute("category"));
}
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
}
}
You can also keep xml file in your assets folder and parse it: Use if else/ switch condition in parsing steps otherwise it will take much time ;)
Example:
final InputSource inputSource = new InputSource();
inputSource.setByteStream(getAssets().open("file.xml"));
inputSource.setByteStream(getAssets().open("file.xml"));
No comments:
Post a Comment