android xml file modifying - android

I receive a XML string from server that is structured like this:
<item_list>
<category>
<item id="1" name="name1" base64="base64String1" />
<item id="2" name="name2" base64="base64String2" />
<item id="3" name="name3" base64="base64String3" />
<item id="4" name="name4" base64="base64String4" />
........
</category>
<category>
........
</category>
<item_list>
What I need to do is this: when I first read the string, read the Base64 strings, save them in a file and then remove them from this string. And then write this string to a XML file. So after that this XML will look like:
<item_list>
<category>
<item id="1" name="name1" />
<item id="2" name="name2" />
<item id="3" name="name3" />
<item id="4" name="name4" />
........
</category>
<category>
........
</category>
<item_list>
Which parser show I use for reading and deleting the Base64 strings? which is the best for this?
And if someone could give me an example or a tutorial how to do this, it would be great.

You can use XPath for that with the expression query "//*[#base64]".
try {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
builderFactory.setNamespaceAware(true);
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document document = builder.parse(new File("your_xml.xml"));
XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "//*[#base64]";
NodeList nodes = (NodeList) xpath.evaluate(expression, document, XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
String base64 = element.getAttribute("base64");
element.removeAttribute("base64");
}
String newXML = getStringFromNode(document);
}
catch (Exception e) {
}
getStringFromNode method
public static String getStringFromNode(Node root) {
StringBuilder result = new StringBuilder();
if (root.getNodeType() == 3)
result.append(root.getNodeValue());
else {
if (root.getNodeType() != 9) {
StringBuffer attrs = new StringBuffer();
for (int k = 0; k < root.getAttributes().getLength(); ++k) {
attrs.append(" ").append(
root.getAttributes().item(k).getNodeName()).append(
"=\"").append(
TextUtils.htmlEncode(root.getAttributes().item(k).getNodeValue()))
.append("\" ");
}
result.append("<").append(root.getNodeName()).append(" ")
.append(attrs).append(">");
} else {
result.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
}
NodeList nodes = root.getChildNodes();
for (int i = 0, j = nodes.getLength(); i < j; i++) {
Node node = nodes.item(i);
result.append(getStringFromNode(node));
}
if (root.getNodeType() != 9) {
result.append("</").append(root.getNodeName()).append(">");
}
}
return result.toString();
}
EDITED
The same could be used for parsing the String also. See my method below which will parse the String as DOM Document. Now you can use this Document as input for your XPath.
public static Document ReadDocument(String xml)
{
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
StringReader reader = new StringReader(xml);
is.setCharacterStream(reader);
doc = db.parse(is);
} catch (Exception e) {
Log.e("Error", "Error while Parsing Document", e);
return null;
}
return doc;
}

Minor improvements for Vivek's function -> Handle CDATA + Use field constants:
public static String getStringFromNode(Node root) throws IOException
{
StringBuilder result = new StringBuilder();
if (root.getNodeType() == Node.TEXT_NODE)
result.append(root.getNodeValue());
else if(root.getNodeType() == Node.CDATA_SECTION_NODE)
result.append("<![CDATA["+root.getNodeValue()+"]]>");
else {
if (root.getNodeType() != Node.DOCUMENT_NODE) {
StringBuffer attrs = new StringBuffer();
for (int k = 0; k < root.getAttributes().getLength(); ++k) {
attrs.append(" ").append(
root.getAttributes().item(k).getNodeName()).append(
"=\"").append(
root.getAttributes().item(k).getNodeValue())
.append("\" ");
}
result.append("<").append(root.getNodeName()).append(" ")
.append(attrs).append(">");
} else {
result.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
}
NodeList nodes = root.getChildNodes();
for (int i = 0, j = nodes.getLength(); i < j; i++) {
Node node = nodes.item(i);
result.append(getStringFromNode(node));
}
if (root.getNodeType() != Node.DOCUMENT_NODE) {
result.append("</").append(root.getNodeName()).append(">");
}
}
return result.toString();
}

Related

Dom parsing for Android

I want to parse XML which is received from a .net web service and store the parsed data into a string array. I tried so many times but the loop is terminating after one execution without any exception.
The XML which is received from web service is attached here.
<DocumentElement>
<PictureList>
<Id>1</Id>
<WorkId>1</WorkId>
<PictureUrl>"~/Admin/"</PictureUrl>
<Status>Active</Status>
<CreatedDateTime>2015-11-21T00:00:00+00:00</CreatedDateTime>
</PictureList>
</DocumentElement>
code which is used for parsing is given below
public void pictures(String st) {
DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(st)));
Element env = doc.getDocumentElement();
NodeList nl = env.getElementsByTagName("PictureList");
lengthsem = nl.getLength();
length = 0;
Node n = nl.item(0);
NodeList nl_suc = n.getChildNodes();
length = nl_suc.getLength();
String[][] semres;
String semdata[][] = new String[lengthsem][36];
for (int i = 0; i < lengthsem; i++) {
n = nl.item(i);
nl_suc = n.getChildNodes();
length = nl_suc.getLength();
int count = 0;
for (int j = 0; j < length; j++) {
System.out.println("length inndr" +length);
Node n_suc = nl_suc.item(j);
String lab = n_suc.getNodeName();
Log.e("lab",lab);
Log.e("fhkhgfgfkhg", n_suc.getNodeName());
if (n_suc.getNodeType() == Node.ELEMENT_NODE) {
sem = Webxml.getElementText((Element) n_suc);
Log.e("iloufhkhghjk,ldlfdlll", sem);
Log.e("fhkhghjk,ldlfdlll", lab);
Node hasSub = nl_suc.item(10);
Log.e("fhkhghjksunbb", hasSub.getNodeName());
String sub = Webxml.getElementText((Element) hasSub);
if (lab.equals("Id")) {
semdata[i][0] = sem;
System.out.println("0 " + lab + i);
success = "true";
try {
j++;
System.out.println(j + "jvalueee");
}catch (Exception e){
System.out.println("exception");
}
Log.e("fhkhghjk,ldlfdlll", lab);
} else if (lab.equals("WorkId")) {
semdata[i][1] = sem;
System.out.println("0 " + lab + i);
success = "true";
Log.e("fhkhghjk,ldlfdlll", lab);
} else if (lab.equals("PictureUrl")) {
semdata[i][2] = sem;
System.out.println("0 " + lab + i);
success = "true";
Log.e("fhkhghjk,ldlfdlll", lab);
} else if (lab.equals("CreatedDateTime")) {
semdata[i][3] = sem;
System.out.println("0 " + lab + i);
success = "true";
Log.e("fhkhghjk,ldlfdlll", lab);
} else {
System.out.println("test111");
break;
}
}
}
}
Well i worked some kind of same data so i can suggest you this way. you can use it also.
String[][] strarray = new String[0][10];
try {
mDbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = mDbf.newDocumentBuilder();
is.setCharacterStream(new StringReader(xml));
mDocument = db.parse(is);
mDocument.getDocumentElement().normalize();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
NodeList nodeList = mDocument.getElementsByTagName("PictureList");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
strarray[0][i] = getValue("Id", element);
strarray[0][i] = getValue("WorkId", element));
strarray[0][i] = getValue("PictureUrl", element));
strarray[0][i] = getValue("Status", element));
strarray[0][i] = getValue("CreatedDateTime", element));
}
}
public String getValue(String stag, Element mElement) {
String value = "";
NodeList nlList = mElement.getElementsByTagName(stag).item(0)
.getChildNodes();
Node nValue = (Node) nlList.item(0);
if (nValue != null) {
value = nValue.getTextContent();
}
return value;
}
I changed it for string array. so it can be logically wrong somewhere.

traverse nested xml file android

I'm trying to traverse a nested XML string in Android that looks like this:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Results>
<Result>
<Questions>
<Question>Where can I get the local variable</Question>
<Answer>In the local method</Answer>
<AverageRating>3.0</AverageRating>
</Questions>
<Keywords>
<Keyword>Methods</Keyword>
<Keyword>Returns</Keyword>
<Keyword>Void</Keyword>
</Keywords>
</Result>
<Result>
<Questions>
<Question>How can I do a nested for loop</Question>
<Answer>Easy</Answer>
<AverageRating>2.5</AverageRating>
</Questions>
<Keywords>
<Keyword>Methods</Keyword>
<Keyword>Returns</Keyword>
<Keyword>Void</Keyword>
<Keyword>Methods</Keyword>
<Keyword>Returns</Keyword>
</Keywords>
</Result>
with the following Android code:
try
{
//Creates the document
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(serverResult)));
//optional, but recommended
//read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
document.getDocumentElement().normalize();
//Look at root node's type (e.g. <query> or <login> or <add>)
String rootNode = document.getDocumentElement().getNodeName().toString();
if (rootNode.equals("Results"))
{
String Question = "";
String Answer = "";
String AverageRating = "";
float rating = 0;
String keyword = "";
NodeList nList = document.getElementsByTagName("Result");
for (int i = 0; i < nList.getLength(); i++)
{
Node nodes = nList.item(i);
if (nodes.getNodeType() == Node.ELEMENT_NODE)
{
Element element = (Element) nodes;
NodeList list = document.getElementsByTagName("Questions");
for (int value = 0; value < list.getLength(); value++)
{
Node node = list.item(value);
if (node.getNodeType() == Node.ELEMENT_NODE)
{
Element eElement = (Element) node;
Question = getValue("Question", eElement);
Answer = getValue("Answer", eElement);
AverageRating = getValue("AverageRating", eElement);
rating = Float.parseFloat(AverageRating);
}
}
}
NodeList keywordNode = document.getElementsByTagName("Keywords");
String keywords = "";
for (int y = 0; y < keywordNode.getLength(); y++)
{
Node node = keywordNode.item(y);
if (node.getNodeType() == Node.ELEMENT_NODE)
{
Element element = (Element) node;
NodeList ModList = document.getElementsByTagName("Keyword");
int count = ModList.getLength();
for (int b = 0; b < count; b++)
{
keyword = element.getElementsByTagName("Keyword").item(b).getTextContent();
keywords = keywords + keyword + "\n";
}
}
items.add(new Question(Question, Answer, rating, keywords));
}
}
}
}
catch (Exception e)
{
String s = e.getMessage();
publishProgress(s);
}
What I'm trying to achieve is for each question of each respective results in the Result tag of my XML, I want to get the question (and it's details) and the respective keywords, adding each to the Question class, then repeat for the next result from Results tag. Can someone please help with my code and show me where I'm going wrong?
Try importing these:
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
by downloading them at this site: http://www.xmlpull.org/
Then, try a code structure like this:
String XMLin;
XmlPullParserFactory factory;
String tag;
ArrayList<Question> questions = new ArrayList<Question>();
try {
XMLin = readString(instream);
} catch (IOException e1) {
// TODO Auto-generated catch block
XMLin = "Something went wrong";
}
try {
// Set up the Class that will be parsing the xml file
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(new StringReader (XMLin));
// Get the first event type
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
// While we have not reached the end of the document, check for start tags
if (eventType == XmlPullParser.START_TAG) {
tag = xpp.getName();
if (tag.equals("Questions") && eventType == XmlPullParser.START_TAG) {
Question question = new Question();
do {
if (tag.equals("Question")) {
// Add question text to question
eventType = xpp.next();
String text = xpp.getText(); // Text between tags
} else if (tag.equals("Answer")) {
eventType = xpp.next();
String text = xpp.getText(); // Text between tags
} else if (tag.equals("AvergaeRating") {
eventType = xpp.next();
String text = xpp.getText(); // Text between tags
}
eventType = xpp.next();
if (eventType == XmlPullParser.TEXT) {
tag = xpp.getText();
} else {
tag = xpp.getName();
}
} while (!tag.equals("Questions"))
questions.add(question);
}
}
}
This is a modified example of something I used to parse through XML. Essentially, check for the tag name and event (whether it's a start tag or end tag, etc) and then perform that actions you want depending on those two values, such as add the text inbetween into a Question object or whatnot.
I managed to use this code:
try
{
//Creates the document
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(serverResult)));
//optional, but recommended
//read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
document.getDocumentElement().normalize();
//Look at root node's type (e.g. <query> or <login> or <add>)
String rootNode = document.getDocumentElement().getNodeName().toString();
if (rootNode.equals("Results"))
{
//Any methods which need to be called that will be used to query the database
//Always sending the String XML through as a parameter
//Look at the child node
String Question = "";
String Answer = "";
String AverageRating = "";
float rating = 0;
String keywords = "";
NodeList nList = document.getElementsByTagName("Questions");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++)
{
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE)
{
Element eElement = (Element) nNode;
Question = getValue("Question", eElement);
Answer = getValue("Answer", eElement);
AverageRating = getValue("AverageRating", eElement);
rating = Float.parseFloat(AverageRating);
NodeList List = document.getElementsByTagName("Keywords");
for (int a = 0; a < List.getLength(); a++)
{
Node node = List.item(temp);
if (node.getNodeType() == Node.ELEMENT_NODE)
{
Element element = (Element) node;
String Keyword = element.getElementsByTagName("Keyword").item(0).getTextContent();
keywords = keywords + Keyword + "\n";
}
}
}
items.add(new Question(Question, Answer, rating, keywords));
}
}
}
catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
which then get's each individual question (and all their information - question, answer, rating) and well as the respective keywords for that question and add to a Question object, then loop back. I wasn't putting the keywords XML parse within the questions for loop. Hopefully this helps someone who is struggling with similar problems.

android XML Parsing with multiple child nodes

I am trying to parse an xml but it is returning all the chld nodes that have tag "nature".But I just want to only those nodes whose cat is selcted.
My xml looks like :-
<NatureList>
<NatureCategory cat="Crimes Against People">
<Nature>
<Name>Aggravated Assault</Name>
</Nature>
<Nature>
<Name>Annoyance Phone Calls</Name>
</Nature>
<NatureCategory>
<NatureCategory ...NatureCategory>
and parsing is done like this :
Document doc = XmlParser.getDomElement(xml);
NodeList n = doc.getElementsByTagName("NatureCategory");
try {
for(int i=0; i<n.getLength();i++)
{
Element e = (Element) n.item(i);
if(e.getAttribute("cat").equals(spinn.getSelectedItem().toString()))
{
Log.i("sub1", spinn.getSelectedItem().toString() );
NodeList n1 = doc.getElementsByTagName("Nature");
for(int j=0; j<n1.getLength();j++)
{
Element e1 = (Element) n1.item(j);
subcategory.add(getValue(e1, "Name"));
}
}
// subcategory.add()
}
}
nodes1 = doc.getElementsByTagName("NatureList");
for (int i = 0; i < nodes1.getLength(); i++) {
ObjectClass cgro = new ObjectClass();
Element e = (Element)nodes1.item(i);
cgro.NatureCategory = XMLfunctions.getValue(e, "NatureCategory");//here u can compare with your spinner string if match then parse this NatureCategory or save oe any logic which u like
nodes1a = doc.getElementsByTagName("cat");
for(int j = 0; j < nodes1a.getLength(); j++ ){
ObjectClass1 cgro1 = new ObjectClass1();
Element e2= (Element) nodes1a.item(j);
cgro1.cat= XMLfunctions.getCharacterDataFromElement(e2);
ArrayListClass.ItemList1.add(cgro1);
}
ArrayListClass.ItemList2.add(cgro);
}
and class use for this
public class XMLfunctions {
public final static Document XMLfromString(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
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
*/
I think if form your XML like this it would be better:
<NatureList>
<NatureCategory>
<cat>Crimes Against People</cat>
<Nature>
<Name>Aggravated Assault</Name>
</Nature>
<Nature>
<Name>Annoyance Phone Calls</Name>
</Nature>
<NatureCategory>
Then get the cat tag and then test it.

xml parsing using DOM parser

I need to parse document using DOM parser in android. I was unable to print all the node values
My Sample XML is:`
<xml_api_reply version="1">
<news module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0">
<title data="Top Stories"/>
<section_type data="0"/>
<news_entry>
<title data="BSE Sensex breaches 19000, Nifty above 5800"/>
<url data="http://in.reuters.com/article/2012/10/04/sensex-above-19000-on-reform-hopes- idINDEE89301O20121004"/>
<snippet data="| MUMBAI (Reuters) - The Nifty rose above 5800 points on Thursday, joining the Sensex in breaching key psychological levels, after continued government reform measures sparked hopes for continued action. Banks led gainers, with ICICI Bank (ICBK."/>
<source data="Reuters India"/>
<date data="3 hours ago"/>
<num_related data="145"/>
<cluster_url data="http://google.co.in/news/story?ncl=da6VmeBXmuquikM&hl=en"/>
</news_entry>
<news_entry>
<title data="Uncertainty over Kingfisher resuming operations tomorrow"/>
<url data="http://www.hindustantimes.com/India-news/NewDelhi/Uncertainty-over- Kingfisher-resuming-operations-tomorrow/Article1-939628.aspx"/>
<snippet data="Hopes of ailing Kingfisher Airlines resuming operations on Friday has faded with last ditch efforts by the management to persuade striking engineers and pilots to return to work failing to end the deadlock over the issue of non-payment of salaries for ..."/>
<source data="Hindustan Times"/>
<date data="1 hour ago"/>
<num_related data="993"/>
<cluster_url data="http://google.co.in/news/story?ncl=dzf460GzYKTOyxM&hl=en"/>
</news_entry>
</news>
</xml_api_reply>`
and I am using following code to parse the xml
xmlactivity.java
public class AndroidXMLParsingActivity extends ListActivity {
// All static variables
static final String URL = "http://www.google.co.in/ig/api?news&hl=en";
// XML node keys
static final String KEY_ITEM = "news"; // parent node
//static final String KEY_ID = "news_entry";
static final String KEY_NAME = "title ";
static final String KEY_COST = "url ";
static final String KEY_DESC = "snippet";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
//map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
//map.put(KEY_COST, parser.getValue(e, KEY_COST));
//map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
/* ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] {
R.id.name, R.id.desciption, R.id.cost });*/
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_NAME }, new int[] {
R.id.name});
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
//String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
//String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
//in.putExtra(KEY_NAME, name);
//in.putExtra(KEY_COST, cost);
in.putExtra(KEY_DESC, description);
startActivity(in);
}
});
and xmlParser.java
public class XMLParser {
// constructor
public XMLParser() {
}
/**
* Getting XML from URL making HTTP request
* #param url string
* */
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
/**
* Getting XML DOM element
* #param XML string
* */
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} 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 doc;
}
/** Getting node value
* #param elem element
*/
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
/**
* Getting node value
* #param Element node
* #param key string
* */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
}
please help me . what is the problem and suggestion
thanks in advance!!!!!!!!!
//Try this code..
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
URLConnection conn = null;
InputStream inputStream = null;
URL urls = new URL(url);
conn = urls.openConnection();
conn.setConnectTimeout(10000);
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setRequestMethod("GET");
httpConn.setConnectTimeout(10000);
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
StringWriter writer=new StringWriter();
String line="";
while ( null!=(line=in.readLine())){
writer.write(line);
}
xml =writer.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return xml;
}
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
doc = db.parse(new InputSource(new StringReader(xml)));
doc.normalize();
//InputSource is = new InputSource();
// is.setCharacterStream(new StringReader(xml));
// doc = db.parse(is);
} 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 doc;
}
public final String getElementValue(Node elem) {
Node child;
if (elem != null) {
if (elem.hasChildNodes()) {
for (child = elem.getFirstChild(); child != null; child = child
.getNextSibling()) {
if (child.getNodeType() == Node.TEXT_NODE || child.getNodeType() == Node.CDATA_SECTION_NODE) {
return child.getTextContent();
}
}
}
}
return "";
}
// All static variables
static final String URL = "http://www.google.co.in/ig/api?news&hl=en";
// XML node keys
static final String KEY_ITEM = "news"; // parent node
static final String KEY_ID = "news_entry";
static final String KEY_NAME = "title";
static final String KEY_COST = "url";
static final String KEY_DESC = "snippet";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
for (int i = 0; i < nl.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
NamedNodeMap attributes = e.getAttributes();
System.out.println("attrlength"+attributes.getLength());
for (int a = 0; a < attributes.getLength(); a++)
{
Node theAttribute = attributes.item(a);
System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());
}
NodeList nl1=e.getElementsByTagName(KEY_ID);
System.out.println("keyId"+nl1.getLength());
for(int j=0;j<nl1.getLength();j++)
{
Element e1 = (Element) nl1.item(j);
NodeList n = e1.getElementsByTagName(KEY_NAME);
for (int k = 0; k < n.getLength(); k++) {
Element e2 = (Element) n.item(k);
// System.out.println("node Title value"+e2.getNodeName());
NamedNodeMap attributes2 = e2.getAttributes();
// System.out.println("attrlength"+attributes2.getLength());
for (int a = 0; a < attributes2.getLength(); a++)
{
Node theAttribute = attributes2.item(a);
System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());
}
}
NodeList n1 = e1.getElementsByTagName(KEY_COST);
// System.out.println("title "+n.getLength());
for (int k = 0; k < n1.getLength(); k++) {
Element e2 = (Element) n1.item(k);
// System.out.println("node Url value");
NamedNodeMap attributes2 = e2.getAttributes();
// System.out.println("attrlength"+attributes2.getLength());
for (int a = 0; a < attributes2.getLength(); a++)
{
Node theAttribute = attributes2.item(a);
System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());
}}
NodeList n2 = e1.getElementsByTagName(KEY_DESC);
// System.out.println("title "+n.getLength());
for (int k = 0; k < n2.getLength(); k++) {
Element e2 = (Element) n2.item(k);
// System.out.println("node snippet value"+e2.getNodeName());
NamedNodeMap attributes2 = e2.getAttributes();
// System.out.println("attrlength"+attributes2.getLength());
for (int a = 0; a < attributes2.getLength(); a++)
{
Node theAttribute = attributes2.item(a);
System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());
}
}
}
menuItems.add(map);
}
}

Getting content of a XML node by the attribute

I have a XML file like this:
<?xml version="1.0"?>
<settings>
<mail id="sender">
<host>content here</host>
<port>25</port>
<account>tmt#example.com</account>
<password>password</password>
</mail>
<mail id="receiver">
<account>tmt#example.com</account>
</mail>
<mail id="support">
<account>tmt#example.com</account>
</mail>
</settings>
How can I get the attribute of each element, parse the content of each element and save the content in SharedPreference
This is what I've done so far:
The Contructor:
public ReadConfig(Context context, ProgressBar progressBar) throws ParserConfigurationException, SAXException, IOException {
this.context = context;
this.progressBar = progressBar;
folders = new CreateApplicationFolder();
dbf = DocumentBuilderFactory.newInstance();
db = dbf.newDocumentBuilder();
doc = db.parse(new File(folders.getPathToNode() + "/settings_config.xml"));
doc.getDocumentElement().normalize();
}
And my doInBackground method
#Override
protected String doInBackground(String... params) {
Log.i("ROOT NODE: ", doc.getDocumentElement().getNodeName());
NodeList listOfMail = doc.getElementsByTagName("mail");
int totalMail = listOfMail.getLength();
Log.i("LENGTH: ", Integer.toString(totalMail));
for(int i = 0; i < totalMail; i++) {
Node firstMailSetting = listOfMail.item(i);
}
}
From the LogCat I know that there are three elements, which is correct.
import org.w3c.dom.Element;
for(int i = 0; i < totalMail; i++) {
Node firstMailSetting = listOfMail.item(i);
Element e = (Element) firstMailSetting ;
String acc = getTagValue("account", e); <-----
}
private String getTagValue(String sTag, Element eElement) {
try {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
}
catch (Exception e) {
return "";
}
}

Categories

Resources