XML (eXtensible Markup Language) is platform independent file having hierarchical structure of elements to hold meaningful data. Parser is used to read, search, and edit information from XML document as XML document will do anything on its own.Simple API for XML (SAX) is one of the parser. It is sequential event driven, fast, memory intensive, read only API available to deal with XML. Follow these steps:
1. Creating XML document
2. Java Program to search information
3. Output
1. Creating XML document
<?xml version="1.0"?> <addressbook> <record> <name>C.Chandran</name> <city>Koimattur</city> </record> <record> <name>Prathmesh</name> <city>Ichalkaranji</city> </record> </addressbook>
2. Java Program to search information
import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.Attributes; import java.util.*; import java.io.*; public class searchxml extends DefaultHandler { static Scanner sc=new Scanner(new InputStreamReader(System.in)); int flag=0; String temp; static String categary; static String skey; public void startElement(String uri, String local, String row, Attributes attrs) throws SAXException { } public void characters(char []ch, int start, int len) throws SAXException { temp=new String(ch,start,len); } public void endElement(String uri, String local, String row) throws SAXException { if(row.equals(categary) && temp.equals(skey)) { System.out.println("Record Found."); flag=1; } } public void endDocument() throws SAXException { if(flag==0) { System.out.println("\nRecord NOT Found."); } } public static void main(String argd[]) { try { searchxml sx=new searchxml(); System.out.print("\n\nEnter Categary : "); categary=sc.next(); System.out.print("\nEnter Search Key : "); skey=sc.next(); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); saxParser.parse("addressbook.xml",sx); }catch(Exception e) { System.out.print(e); } } }
3. Output
Enter Category: name Enter Search Key: Prathmesh Record Found
EmoticonEmoticon