Java parsing XML with sax

Source: Internet
Author: User

MyHandler

package com.heli.xml.sax;/** *  parsing xml with sax Handler */import java.util.arraylist;import  java.util.HashMap;import java.util.List;import java.util.Map;import  org.xml.sax.attributes;import org.xml.sax.saxexception;import org.xml.sax.helpers.defaulthandler; public class myhandler extends defaulthandler {//  stores data for the element being parsed Private map <String, String> map = null;//  stores data private list<map<string for all parsed elements,  String>> list = null;//  the name of the element being parsed string currenttag = null;//   The element value of the element being parsed string currentvalue = null;//  begins parsing the element string nodename =  Null;public myhandler (String nodename)  {// TODO Auto-generated constructor  Stubthis.nodename = nodename;} Public list<map<string, string>> getlist ()  {return list;}   begins parsing the document, which begins the solutionWhen you analyze an XML root element, call the method @overridepublic void startdocument ()  throws saxexception {// todo  auto-generated method stub//system.out.println ("--startdocument ()--");//  initialization maplist  = new arraylist<map<string, string>> ();}   calls this method when it starts parsing each element @overridepublic void startelement (string uri, string  Localname, string qname, attributes attributes)  throws saxexception {//  TODO Auto-generated method stub//  determines that the element being parsed is not the element that begins parsing//system.out.println ("-- Startelement ()--" + qname";if  (Qname.equals (nodeName))  {map = new hashmap <String, String> ();}   Determines whether the element being parsed has a property value, and if so, takes it all out and saves it to the map object, such as: <person id= "00001" ></person>if  ( Attributes != null && map != null)  {for  (int i =  0; i < attributes.getlength ();  i++)  {map.put (Attributes.getqname (i),  attributes.getvalue (i));}} This method is called when the element currenttag = qname; //  is parsing}//  resolves to the content of each element @overridepublic void  Characters (Char[] ch, int start, int length)  throws saxexception {//  todo auto-generated method stub//system.out.println ("--characters ()--");if  ( Currenttag != null && map != null)  {currentvalue = new  string (ch, start, length);//  If the content is not empty and spaces, and is not a newline character, the element name and value are stored in the map if  (currentvalue ! = null && !currentvalue.trim (). Equals ("")  && !currentvalue.trim (). Equals ("\ n"))  {map.put (Currenttag, currentvalue);//system.out.println ("-----"  + currenttag  +  " "  + currentvalue);}   The current element has been parsed, empty it for parsing currenttag = null;currentvalue = null of the next element;}}   This method is called at the end of each element @overridEpublic void endelement (string uri, string localname, string qname)   Throws saxexception {// todo auto-generated method stub//system.out.println ("-- EndElement ()---" + qname";//  determines whether the element tag is the end of a node if  (qname.equals (nodeName))  {list.add (map ); map = null;}}   Ends parsing the document, which is called when parsing the root element end tag @overridepublic void enddocument ()  throws saxexception  {// todo auto-generated method stub//system.out.println ("--endDocument ()--"); Super.enddocument ();}}

Saxservice

Package com.heli.xml.sax;/** * Packaging parsing business class */import Java.util.list;import Java.util.map;import Javax.xml.parsers.saxparser;import Javax.xml.parsers.saxparserfactory;public class SaxService {public static List <map<string, string>> ReadXML (string uri, string NodeName) {try {//Create a factory object that parses XML saxparserfactory Parserfactory = Saxparserfactory.newinstance ();//Create an object that parses XML saxparser parser = Parserfactory.newsaxparser ();// Create a parsing helper class MyHandler MyHandler = new MyHandler ("Uncall");p Arser.parse (URI, MyHandler); return myhandler.getlist ();} catch (Exception e) {e.printstacktrace ();} finally {}return null;}}

Xmlsaxtest

package com.heli.xml.sax;/** *  Program Entry  */import java.util.ArrayList;import  Java.util.hashmap;import java.util.iterator;import java.util.map;public class xmlsaxtest  {/** *  @param  args */public static void main (String[] args)  {ArrayList<Map<String, String>> list =  (Arraylist<map<string,  String>>)  saxservice.readxml ("E:\\test.xml",  "class");for  (int i = 0 ;  i < list.size ();  i++)  {HashMap<String, String> temp =  (hashmap<string, string>)  list.get (i);iterator<string> iterator =  Temp.keyset (). Iterator ();while  (Iterator.hasnext ())  {string key = iterator.next (). ToString (); String value = temp.get (key); System.out.println ("Key:" +key +  "--value:"  + value );}} System.out.prinTLN ("--------------------------------------"); System.out.println (List.tostring ());}}

Test.xml

<?xml version= "1.0" encoding= "Utf-8"?><uncall> <result>1</result> <OnClickCall> < Response>success</response> <ActionID>123456</ActionID> <message>originate Successfully queued</message> </OnClickCall></uncall>


Java parsing XML with sax

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.