XML File Creation With Our Own Tags

Quickly share your Android Code Snippets here...

XML File Creation With Our Own Tags

Postby Jhon » Wed Mar 03, 2010 7:22 am

public String CreateXMLFile(Request aRequest)
{
//create a new file called "temp.xml" in the SD card
File lXmlfile = new File(Environment.getExternalStorageDirectory() +
"/" + "temp.xml");

try{
if(!lXmlfile.exists())
lXmlfile.createNewFile();

}catch(IOException e){
Log.e("IOException", "exception in createNewFile() method");
return null;
}


//we have to bind the new file with a FileOutputStream
FileOutputStream lFileOutputStream = null;

try{
lFileOutputStream = new FileOutputStream(lXmlfile);

//we create a XmlSerializer in order to write xml data
iXmlSerializer = Xml.newSerializer();

//we set the FileOutputStream as output for the serializer, using UTF-8 encoding
iXmlSerializer.setOutput(lFileOutputStream, "UTF-8");

//Write <?xml declaration with encoding (if encoding not null) and standalone flag (if standalone not null)
iXmlSerializer.startDocument(null, null);

//set indentation option
iXmlSerializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);

iXmlSerializer.startTag(null, "MethodCall");

iXmlSerializer.startTag(null, "MethodName");

iXmlSerializer.text(aRequest.PostMethod());

iXmlSerializer.endTag(null, "MethodName");


iXmlSerializer.startTag(null, "Params");

String lParameters[] = aRequest.PostParameters();

if(lParameters != null)
{
for(int i = 0; i < lParameters.length; i++)
{
iXmlSerializer.startTag(null, "Param");

iXmlSerializer.startTag(null, "Value");

iXmlSerializer.startTag(null, "String");

iXmlSerializer.text(lParameters[i]);

iXmlSerializer.endTag(null, KString);

iXmlSerializer.endTag(null, "Value");

iXmlSerializer.endTag(null, "Param");
}
}

iXmlSerializer.endTag(null, "Params");

iXmlSerializer.endTag(null, "MethodCall");

iXmlSerializer.endDocument();

//write xml data into the FileOutputStream
iXmlSerializer.flush();

//finally we close the file stream

lFileOutputStream.flush();

lFileOutputStream.close();

lFileOutputStream = null;

} catch (Exception e) {

Log.e("Exception","error occurred while creating xml file");
return null;
}

return lXmlfile.getAbsolutePath();
}


By Using the above function we can generate a XML file with our own tags.
Happy Journey
Jhon
Jhon
Freshman
Freshman
 
Posts: 9
Joined: Wed Sep 09, 2009 4:06 pm

Top

Return to Code Snippets for Android

Who is online

Users browsing this forum: No registered users and 4 guests