SAX and XML file, how to?
Hi,
I'm going to use JAXP and SAX to read my application XML config file.
But I'm lost, I don't know how to read the elements.
How does it function, do I have to put in the startElement() method as many "if" as entitys I need to process?
And how can I guess if an element belongs (is inside) one element or another?
Example:
<program>
<printer id="xx" type="aa">
<path> /aa/cc </path>
</printer>
<source>
<path> /aa/bb </path>
</source>
</program>
for this XML, how would you code it? this way?
startElement (String uri, String localName, String qName, Attributes attributes) {
if (localname.equals("printer")) {
//get printer attributes
} else if (localname.equals("source")) {
//get source attributes
}
}
thanks!
[923 byte] By [
txatia] at [2007-11-27 6:01:37]

# 4
i have one sample code through which u can read the elements from xml file.
// File SaxLister.java
import java.io.IOException;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
public class SAXLister {
public static void main(String[] args) throws Exception
{
new SAXLister(args);
}
public SAXLister(String[] args) throws SAXException, IOException
{
XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
// should load properties rather than hardcoding class name
parser.setContentHandler(new PeopleHandler( ));
parser.parse(args.length == 1 ? args[0] : "parents.xml");
}
/** Inner class provides DocumentHandler
*/
class PeopleHandler extends DefaultHandler
{
boolean parent = false;
boolean kids = false;
public void startElement(String nsURI, String localName,
String rawName, Attributes attributes) throws SAXException {
//System.out.println("docEvents" + "startElement: " + localName + ","
// + rawName);
// Consult rawName since we aren't using xmlns prefixes here.
if (rawName.equalsIgnoreCase("name"))
parent = true;
if (rawName.equalsIgnoreCase("children"))
kids = true;
}
public void characters(char[] ch, int start, int length) {
if (parent) {
System.out.println("Parent: " + new String(ch, start, length));
parent = false;
} else if (kids) {
System.out.println("Children: " + new String(ch, start, length));
kids = false;
}
}
/** Needed for parent constructor */
public PeopleHandler( ) throws org.xml.sax.SAXException {
super( );
}
}
}
// File people.xml
<?xml version="1.0"?>
<people>
<person>
<name>Ian Darwin</name>
<email>http://www.darwinsys.com/</email>
<country>Canada</country>
</person>
<person>
<name>Another Darwin</name>
<email type="intranet">afd@node1</email>
<country>Canada</country>
</person>
</people>
I hope this gives u a better understanding of how SAX parser works..
Kindly note u need xml.jar and xerces.jar in ur classpath to run above program.
Regards,
Nikunj