Fri Oct 26, 2012 2:24 pm
<?xml version="1.0" encoding="UTF-8"?>
<Employees>
<Employee EmploymentDate="12-11-2001">
<Name>joseph</Name>
<DeptID>21</DeptID>
<Title>Senior</Title>
</Employee>
<Employee EmploymentDate="3-2-2004">
<Name>Tom</Name>
<DeptID>23</DeptID>
<Title>junior</Title>
</Employee>
</Employees>
import java.util.jar.Attributes;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class SAX_Parse extends DefaultHandler {
private String value;
public static void main(String[] args) {
// Printing the headers of the XML file
System.out.println("EmploymentDate\tName\tDeptID\tTitle\n");
//
new SAX_Parse().XMLStartParse();
}
public void XMLStartParse() {
try {
// getting SAXParserFactory instance
SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
// Getting SAXParser object from AXParserFactory instance
SAXParser saxParser = saxParserFactory.newSAXParser();
// Parsing XML Document by calling parse method of SAXParser class
saxParser.parse("C:\\employees.xml", this);
} catch (Exception e) {
e.printStackTrace();
}
}
// Overriding characters() method of DefaultHandler class
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
value = new String(ch, start, length);
}
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
value = "";
if (qName.equalsIgnoreCase("Employee")) {
System.out.print(attributes.getValue("EmploymentDate") + "\t");
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equalsIgnoreCase("Name")) {
System.out.print(value + "\t");
}
if (qName.equalsIgnoreCase("EmpID")) {
System.out.print(value + "\t");
}
if (qName.equalsIgnoreCase("Title")) {
System.out.print(value + "\n");
}
}
}
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com
Powered by phpBB © phpBB Group.