Parse XML using SAX

Source: Internet
Author: User

XML to be parsed
 
 
Java code
<? Xml version = "1.0" encoding = "UTF-8"?>
<Musices>
<Music>
<Name> Hello </name>
<Size> 8622 </size>
</Music>
<Music>
<Name> World </name>
<Size> 2000 </size>
</Music>
</Musices>
 
Inherit DefaultHandler
 
 
Java code
Package cn.edu. xml;
 
Import org. xml. sax. Attributes;
Import org. xml. sax. SAXException;
Import org. xml. sax. helpers. DefaultHandler;
 
Public class MyXmlUtils extends DefaultHandler {
Private boolean isName = false;
Private boolean isSize = false;

Private String myname;
Private String mysize;
@ Override
Public void characters (char [] ch, int start, int length)
Throws SAXException {
// TODO Auto-generated method stub
Super. characters (ch, start, length );
If (isName ){
Myname = new String (ch, start, length );
}
If (isSize)
{
Mysize = new String (ch, start, length );
}

}
 
@ Override
Public void endDocument () throws SAXException {
// TODO Auto-generated method stub
Super. endDocument ();
}
 
@ Override
Public void endElement (String uri, String localName, String name)
Throws SAXException {
// TODO Auto-generated method stub
Super. endElement (uri, localName, name );
If (name. equals ("name ")){
System. out. println (myname );
} Else if (name. equals ("size ")){
System. out. println (mysize );}
}
 
@ Override
Public void startDocument () throws SAXException {
// TODO Auto-generated method stub
Super. startDocument ();

}
 
@ Override
Public void startElement (String uri, String localName, String name,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
Super. startElement (uri, localName, name, attributes );
If (name. equals ("name ")){
IsName = true;
System. out. println ("one ");
}
Else if (name. equals ("size ")){
IsSize = true;
System. out. println ("second ");
}

}
 
}
 
 
Parse XML
 
 
Java code
SAXParserFactory sf = SAXParserFactory. newInstance ();
SAXParser sp = sf. newSAXParser ();
MyXmlUtils reader = new MyXmlUtils ();
Sp. parse (new File ("E: \ music. xml"), reader );

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.