Java pull way to generate XML files and parse XML files

Source: Internet
Author: User
Tags tagname xml parser

The pull XML parser has already been integrated into the Android SDK by Google, which is the parser recommended by Google.


If we want to use pull method to generate XML file and parse XML file in Java Desktop, J2ME, etc., we need to use KXML2;


Kxml parser is a small parser based on the ordinary XML pull parser, the official website is http://kxml.org/

The official XML pull parser is http://xmlpull.org/


Experiment begins:

Create a new Java project in Eclipse, where you create a new Libs folder, copy the Kxml2-2.2.2.jar file downloaded from the Web into it, and configure the compilation path;


The XML file style we want to manipulate is as follows:

<?xml version= "1.0" encoding= "UTF-8"?>   <root>    <wisdom id= "1" >  <content> now Nap, You will dream, and now learn, you will dream </content>   <author> Harvard library </author>   </wisdom>  <wisdom id= "2 ">   <content> I waste today, is precisely yesterday perishes the person to pray tomorrow </content>  <author> Harvard library </author>   < /wisdom>    </root>


Each node in the corresponding XML file is described by an entity class:

public class Wisdom {private int id;private string Content;private string Author;public Wisdom () {super ();} Public Wisdom (String content, string author) {super (); this.content = Content;this.author = author;} public Wisdom (int ID, string content, string author) {super (); this.id = Id;this.content = Content;this.author = author;} public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String getcontent () {return content;} public void SetContent (String content) {this.content = content;} Public String Getauthor () {return author;} public void Setauthor (String author) {this.author = author;}}


The core class has two main functions:

1. Parsing

2. Build

Import Java.io.file;import java.io.fileoutputstream;import Java.io.inputstream;import Java.util.ArrayList;import Java.util.list;import Org.kxml2.io.kxmlparser;import Org.kxml2.io.kxmlserializer;import Org.xmlpull.v1.xmlpullparser;import org.xmlpull.v1.xmlserializer;/** * * @author Administrator * */public class PullDem o {/** * parse XML file in input stream * * @param is input stream * @return Parse result set */public list<wisdom> parsexml (InputStream is) {//Declaration return value LIS T<wisdom> wisdomlist = null;//Gets the parsed object Xmlpullparser xmlpullparser = new Kxmlparser (); try {// Sets the encoding of the input stream Xmlpullparser.setinput (IS, "utf-8");//Gets the resolved event type int eventtype = Xmlpullparser.geteventtype ();// Declare a wisdom reference wisdom Wisdom = null;//Determine if the file parsing is complete while (eventtype! = xmlpullparser.end_document) {String tagName = XMLPULLP Arser.getname (); switch (eventtype) {case XmlPullParser.START_DOCUMENT:wisdomList = new arraylist<wisdom> (); Break;case XmlPullParser.START_TAG:if ("Wisdom". Equals (TagName)) {//Create wisdom object wisdom = new Wisdom (); Wisdom.setid ( IntegeR.parseint (Xmlpullparser.getattributevalue (NULL, "id")));} else if ("content". Equals (TagName)) {wisdom.setcontent (Xmlpullparser.nexttext ());} else if ("Author". Equals (TagName) ) {Wisdom.setauthor (Xmlpullparser.nexttext ());} Break;case XmlPullParser.END_TAG:if ("Wisdom". Equals (TagName) && wisdom! = null) {// Add the Wisdom object to the collection to Wisdomlist.add (wisdom); wisdom = null;} break;} Reads the next event EventType = Xmlpullparser.next ();} Close input stream is.close ();} catch (Exception e) {e.printstacktrace ();} return wisdomlist;} /** * Generates an XML file based on the contents of the list * * @param wisdomlist * A list of multiple wisdom objects * @return True indicates a build succeeded, false indicates a build failure */public Boolean createxml (list<wisdom> wisdomlist) {//Use pull parsing to implement//destination file path string filePath = "D:\\wisdoms.xml";// The target file is a filename, a new file (FilePath), or//Gets an XML serialized instance XmlSerializer serializer = new Kxmlserializer ();// File write stream instance FileOutputStream fos = null;try {//Output stream object that creates a file based on a file object fos = new FileOutputStream (file);// Set the output stream and encode serializer.setoutput (FOS, "utf-8");//Set the start of the file Serializer.starTdocument ("UTF-8", true);//Set File start tag Serializer.starttag (null, "root"); for (Wisdom wisdom:wisdomlist) {// Wisdom the start of the label serializer.starttag (null, "wisdom");//Set the properties of the wisdom tag serializer.attribute (NULL, "id", Wisdom.getid () + "") ;//Set Wisdom label Contentserializer.starttag (NULL, "content"); Serializer.text (Wisdom.getcontent ()); Serializer.endtag (NULL, "content");//sets the Ageserializer.starttag (null, "author") of the Wisdom label's Child label; Serializer.text ( Wisdom.getauthor ()); Serializer.endtag (null, "author");//wisdom End of Tag serializer.endtag (null, "wisdom");} Set file end tag Serializer.endtag (null, "root");//end of File Serializer.enddocument (); Serializer.flush (); Fos.close (); return true;} catch (Exception e) {e.printstacktrace (); return false;}}}


Using the core class in the Main method, first generate the XML file on the D disk (Windows operating System) , then parse the XML file and print the parsed collection to the console.

Import Java.io.file;import java.io.fileinputstream;import Java.util.arraylist;import Java.util.List;public class pulltest {public static void main (string[] args) {//************* Initialize list collection * * * * * * start **************arraylist<wisdom > wisdomlist = new arraylist<> (); Wisdom w = new Wisdom (); W.setid (1); W.setcontent ("At this moment, you will dream, and now learn, you will dream"); W.setauthor ("Harvard Library"); Wisdomlist.add (w); w = New Wisdom (); W.setid (2); W.setcontent ("I am deserted today, it is yesterday perishes people pray for Tomorrow"); W.setauthor ("Harvard Library"); Wisdomlist.add (w); w = new Wisdom (); W.setid (3); W.setcontent ("feel too late, exactly the earliest time"); W.setauthor ("Harvard Library"); Wisdomlist.add (w); w = new Wisdom (); W.setid ( 4) w.setcontent ("Do not drag today to tomorrow"), W.setauthor ("Harvard Library"), Wisdomlist.add (w); w = new Wisdom (); W.setid (5); W.setcontent (" Learning pain is temporary, not learned pain is lifelong "); W.setauthor (" Harvard Library "); Wisdomlist.add (w); w = new Wisdom (); W.setid (6); W.setcontent (" Learn this thing, Not lack of time, but lack of effort "); W.setauthor (" Harvard Library "); Wisdomlist.add (w); w = new Wisdom (); W.setid (7); W.setcontent (" Happiness may not rank, but success must be ranked "); W.setauthor (" Harvard Library "); Wisdomlist.add (w); w = new WisDom (); W.setid (8); W.setcontent ("Learning is not the whole of life. But since even part of life-learning is not conquered, what can be done? W.setauthor ("Harvard Library"); Wisdomlist.add (w); w = new Wisdom (); W.setid (9); W.setcontent ("Please enjoy unavoidable pain"); W.setauthor (" Harvard library "); Wisdomlist.add (w); w = new Wisdom (); w.setid; W.setcontent (" The only way to taste the taste of success is to work earlier and diligently than others "); W.setauthor (" Harvard library "); Wisdomlist.add (w); w = new Wisdom (); W.setid, W.setcontent (" No one can casually succeed, it comes from thorough self-management and perseverance "); W.setauthor (" Harvard library "); Wisdomlist.add (w); w = new Wisdom (); W.setid (n); W.setcontent (" Time is passing "); W.setauthor (" Harvard Library "); Wisdomlist.add ( W); w = new Wisdom (); W.setid, W.setcontent ("Now the saliva will be the tears of Tomorrow"); W.setauthor ("Harvard Library"); Wisdomlist.add (w); w = new Wisdom (W.setid); W.setcontent ("The dog learns like a Gentleman"); W.setauthor ("Harvard Library"); Wisdomlist.add (w); w = new Wisdom (); W.setid W.setcontent ("Do not go today, tomorrow will run"), W.setauthor ("Harvard Library"), Wisdomlist.add (w); w = new Wisdom (); W.setid (+); W.setcontent (" The person who invests in the future, is loyal to the reality "); W.setauthor (" Harvard Library "); Wisdomlist.add (w); w = new Wisdom (); w.setid; W.setcontent (" Education represents income "); W.setauthor ("Harvard Library"); Wisdomlist.add (w); w = New Wisdom (W.setid); W.setcontent ("End of day, no More"); W.setauthor ("Harvard Library"); Wisdomlist.add (w); w = new Wisdom (); W.setid W.setcontent ("Even now, opponents keep flipping pages"), W.setauthor ("Harvard Library"), Wisdomlist.add (w); w = new Wisdom (); W.setid (20); W.setcontent ("No hardship, no success"); W.setauthor ("Harvard Library"); Wisdomlist.add (w);//************* Initialize List collection * * * End ************* *//new Pulldemo Object Pulldemo pd = new Pulldemo ();//Generate XML File Pd.createxml (wisdomlist); try {File file = new file ("d:\\ Wisdoms.xml ");//Read file stream fileinputstream fis = new FileInputStream (file);//Call parse XML method to get result set list<wisdom> list = Pd.parsexml (FIS);//cycle print for (Wisdom wisdom:list) {System.out.println (wisdom.getcontent ());}} catch (Exception e) {System.out.println (E.getmessage ());}}}


The experiment is over. Attach the KXML2 jar package here: Kml2-2.2.2.jar


Hope that the above code is helpful to everyone!

Java pull way to generate XML files and parse XML files

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.