xml version="1.0" encoding="UTF-8"?>The java:
< Contacts>
< person id="1">
< Name> encoder
< First name> java
< mobile> 054124587
< Email> codeurjava@gmail.com
< person id="2">
< Name> encoder
< First name> c++
< mobile> 062148795
< Email> codeurcplusplus@gmail.com
import javax.xml.parsers.SAXParser;Execution:
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class ReadFileXML{
public static void main(String argv[]) {
try {
//Get sax parser
SAXParserFactory spfactory = SAXParserFactory.newInstance();
//Get an instance of the parser
SAXParser saxParser = spfactory.newSAXParser();
/*all three methods are declared in the DefaltHandler /> corp
DefaultHandler handler = new DefaultHandler() {
boolean bnom = false;
boolean bprefirst name = false;
boolean bmobile = false;
boolean bemail = false;
/*this method is invoked whenever Parser encounters
an opening tag '<' */
public void startElement(String uri, String localName,
String qName,Attributes attributes) throws SAXException{
if (qName.equalsIgnoreCase("name")) {
bnom = true;
}
if (qName.equalsIgnoreCase("firstname")) {
bfirstname = true;
}
if (qName.equalsIgnoreCase("mobile")) {
bmobile = true;
}
if (qName.equalsIgnoreCase("email")) {
bemail = true;
}
}
/*this method is invoked whenever parser encounters
a closing tag '>' */
public void endElement(String uri, String localName,
String qName) throws SAXException {
if (qName.equalsIgnoreCase("name")) {
bnom = false;
}
if (qName.equalsIgnoreCase("firstname")) {
bfirstname = false;
}
if (qName.equalsIgnoreCase("mobile")) {
bmobile = false;
}
if (qName.equalsIgnoreCase("email")) {
bemail = false;
}
}
/*prints data stored between '<' and '>' */
public void characters(char ch[], int start,
int length) throws SAXException {
if (bnom) {
System.out.println("Name: " +
new String(ch, start, length));
bnom = false;
}
if (bprename) {
System.out.println("First name: " +
new String(ch, start, length));
bfirst name = false;
}
if (bmobile) {
System.out.println("Mobile : " +
new String(ch, start, length));
bmobile = false;
}
if (bemail) {
System.out.println("Email : " +
new String(ch, start, length));
bemail = false;
}
}
};
saxParser.parse("exemple.xml", handler);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Last name: coder
First name: java
Mobile: 054124587
Email: codeurjava@gmail.com
Last name: coder
First name: c++
Mobile: 062148795
Email: codeurcplusplus@gmail.com
Please disable your ad blocker and refresh the window to use this website.