Methods for parsing XML-the methods for parsing xml-the methods for parsing XML-

Source: Internet
Author: User

Methods for parsing XML-the methods for parsing xml-the methods for parsing XML-

Holiday summary cannot stop, insist on .... Next we will summarize the parsing and generation of XMl and json ..
XML parsing Methods: DOM, SAX, JDOM, and DOM4J

The following shows the jar packages for these four methods:
DOM: Now comes in the Java JDK, In the xml-apis.jar package
SAX: http://sourceforge.net/projects/sax/
JDOM: http://jdom.org/downloads/index.html
DOM4J: http://sourceforge.net/projects/dom4j/
The current compilation will start with one-to-one introduction:
SAX: This is my first method...
SAX is an XML parser with high resolution speed and low memory usage. It is very suitable for Android mobile devices.
SAX uses event-driven '. That is to say, it does not need to parse complete documents. In the process of parsing documents in order of content, sax checks whether the currently read characters conform to a part of the XMl syntax. If yes, an event is triggered.
The so-called events are actually some callback methods, which are defined in GefaultHandler.
Resolution Process:
(1) create a SAX Parser
SAXParserFactory factory = SAXParserFactory. newInstance ();
// Reader object, which is obtained from the parser
XMLReader reader = factory. newSAXParser (). getXMLReader ();
(2) Implement DefaultHandler Parsing
The following four methods are implemented:
Void startDocument (), void endDocument (), void startElement (String uri, String localName, string qName, Attributes attr ).
Void endElement (String uri, String localName, string qName)
Android sample code:

Package com. example. xmltest; import java. text. attributedCharacterIterator. attribute; import org. xml. sax. attributes; import org. xml. sax. SAXException; import org. xml. sax. helpers. defaultHandler; // The ulthandlerpublic class MyContentHandler extends extenulthandler {String hisname, address, money, sex, status; String tagName; /*** @ param args */public void startDocument () throws SAXException {Sy Stem. out. println (", begin,");} public void endDocument () throws SAXException {System. out. println (", end,");} // QName (Qualified Name limit?? Name) // sina: blog is QName, which is equivalent to the prefix + ":" + LocalName, and LocalName is blog. // Attributes obtains the tag Attributes. A tag can have multiple Attributes. The id in <worker id = "AD002"> is the public void startElement (String namespaceURI, String localName, String qName, attributes attr) throws SAXException {tagName = localName; System. out. println ("tagName:" + tagName); // The localName attribute returns the local name (element name) of the selected element ). // If the selected node is not an element or attribute, NULL if (localName. equals ("worker") {// obtain all attributes of a tag for (int I = 0; I <attr. getLength (); I ++) {System. out. println (attr. getLocalName (I) + "=" + attr. getValue (I);} // getLocalName (I) is the id getValue (I) is the value behind it} // namespaceURI namespace, obtain the namespace of the tag being parsed. localname is used to differentiate tags. localName is not prefixed. qname is prefixed with public void endElement (String namespaceURI, String localname, String qName) throws SAXException {// get all attributes of a tag If (localName. equals ("worker") {this. printout (); // all output} tagName = "" ;}// get the value. The tagName is already the tag name in startElement... Public void characters (char [] ch, int start, int length) throws SAXException {if (tagName. equals ("name") hisname = new String (ch, start, length ). trim (); else if (tagName. equals ("sex") sex = new String (ch, start, length ). trim (); else if (tagName. equals ("status") status = new String (ch, start, length ). trim (); else if (tagName. equals ("address") address = new String (ch, start, length ). trim (); else if (tagName. equals ("money") {money = new String (ch, start, length ). trim () ;}} private void printout () {System. out. print ("name:"); System. out. println (hisname); System. out. print ("sex:"); System. out. println (sex); System. out. println ("cdv"); System. out. print ("status:"); System. out. println (status); System. out. print ("address:"); System. out. println (address); System. out. print ("money:"); System. out. println (money); System. out. println ();}}

Below is the Activity code:

Package com. example. xmltest; import java. io. stringReader; import javax. xml. parsers. SAXParserFactory; import org. xml. sax. contentHandler; import org. xml. sax. inputSource; import org. xml. sax. XMLReader; import com. example. utils. httpDownloader; import android. app. activity; import android. OS. bundle; import android. view. view; import android. view. view. onClickListener; import android. widget. button; // the corresponding file is in D: \ tomcat-6.0. 43 \ webapps \ voalpublic class XMLActivity extends Activity {private Button parsebutton; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_xml); parsebutton = (Button) findViewById (R. id. parsebutton); parsebutton. setOnClickListener (new ParseButtonListener ();}/*** the network service cannot be applied for in the thread !!!! Another thread * @ author ultra boy */class ParseButtonListener implements OnClickListener {@ Override public void onClick (View v) {// TODO Auto-generated method stub System. out. println ("Startup Thread"); new Thread (new Down ()). start () ;}} class Down implements Runnable {@ Override public void run () {// TODO Auto-generated method stub HttpDownloader hd = new HttpDownloader (); // resultStr returns the file content String resultStr = hd. download ("http: // 192.168.253.1: 8088/voal/test. xml "); // This is the file System in the self-built server. out. println (resultStr); try {// create a SAXParserFactory parser project SAXParserFactory factory = SAXParserFactory. newInstance (); // reader object. Obtain reader XMLReader reader = factory from the parser. newSAXParser (). getXMLReader (); // set the content processor for xmlreader, scan row by row, and call the function. The function to be called is reader in the MyContentHandler implementation class. setContentHandler (new MyContentHandler (); // start parsing the file System. out. println ("START Parsing"); reader. parse (new InputSource (new StringReader (resultStr);} catch (Exception e) {e. printStackTrace ();}}}}

Resolved original file:

<? Xml version = "1.0" encoding = "UTF-8"?> <Workers> <worker id = "AQ01"> <name> Jery </name> <sex> female </sex> <status> Manager </status> <address> Beijing </address> <money> 4000 </money> </worker> <worker id = "AD02"> <name> Lili </name> <sex> female </sex> <status> Director </status> <address> Qingdao </address> <money> 40000 </money> </worker> <worker id = "AD03"> <name> ChaoCaho </name> <sex> male </sex> <status> Chairman </status> <address> Qingdao </address> <money> 400000 </money> </worker> </workers>

Reprinted please indicate the source: http://www.cnblogs.com/jycboy/p/saxparxml.html

Related Article

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.