Sometimes, we need to generate an XML file. There are many ways to generate an XML file. For example, we can use only one stringbuilder to group XML content and then write the content into the file; you can also use the pull parser to generate xml files by using Dom APIs. We recommend that you use the pull parser. 1. Use the pull parser to generate a myitcast. xml file with the same content as the itcast. xml file. The code is below
Public static string writexml (list <person> persons, writer) {xmlserializer serializer = xml. newserializer (); try {serializer. setoutput (writer); serializer. startdocument ("UTF-8", true); // The first parameter is a namespace and can be set to null serializer if no namespace is used. starttag ("", "persons"); For (person: Persons) {serializer. starttag ("", "person"); serializer. attribute ("", "ID", person. GETID (). tostring (); serializer. starttag ("", "name"); serializer. text (person. getname (); serializer. endtag ("", "name"); serializer. starttag ("", "Age"); serializer. text (person. getage (). tostring (); serializer. endtag ("", "Age"); serializer. endtag ("", "person");} serializer. endtag ("", "persons"); serializer. enddocument (); Return writer. tostring ();} catch (exception e) {e. printstacktrace ();} return NULL ;}
Use the following code to generate an XML file ):
File xmlFile = new File("myitcast.xml");FileOutputStream outStream = new FileOutputStream(xmlFile);OutputStreamWriter outStreamWriter = new OutputStreamWriter(outStream, "UTF-8");BufferedWriter writer = new BufferedWriter(outStreamWriter);writeXML(persons, writer);writer.flush();writer.close();
If you only want to get the generated XML string content, you can use stringwriter:
StringWriter writer = new StringWriter();writeXML(persons, writer);String content = writer.toString();
2,
public static void save(List<Person> persons,OutputStream out)throws Exception{XmlSerializer xmlSerializer=Xml.newSerializer();xmlSerializer.setOutput(out, "UTF-8");xmlSerializer.startDocument("UTF-8", true);xmlSerializer.startTag(null, "persons");for(Person person:persons){xmlSerializer.startTag(null, "person");xmlSerializer.attribute(null, "id", person.getId().toString());xmlSerializer.startTag(null, "name");xmlSerializer.text(person.getName());xmlSerializer.endTag(null, "name");xmlSerializer.startTag(null, "age");xmlSerializer.text(person.getAge().toString());xmlSerializer.endTag(null, "age");xmlSerializer.endTag(null, "person");}xmlSerializer.endTag(null, "persons");xmlSerializer.endDocument();out.flush();out.close();}
Call the above method to output the XML file
public void testSavePerson()throws Exception{List<Person> persons=new ArrayList<Person>();persons.add(new Person("zhangss",12,23));persons.add(new Person("xiaoxiao",45,21));persons.add(new Person("zhagnni",10,47));File file=new File(getContext().getFilesDir().toString(),"person.xml");FileOutputStream out=new FileOutputStream(file);new PersonService().save(persons, out);}