使用SAX解析XML文件
2008-01-05 08:58:39 来源:WEB开发网核心提示:/*<PHONEBOOK><PERSON> <NAME>Joe Yin</NAME> <EMAIL>joe@yourserver.com</EMAIL> <TELEPHONE>202-999-9999</TELEPHONE>
/*
<PHONEBOOK>
<PERSON>
<NAME>Joe Yin</NAME>
<EMAIL>joe@yourserver.com</EMAIL>
<TELEPHONE>202-999-9999</TELEPHONE>
<WEB>www.java2s.com</WEB>
</PERSON>
<PERSON>
<NAME>Karol</name>
<EMAIL>karol@yourserver.com</EMAIL>
<TELEPHONE>306-999-9999</TELEPHONE>
<WEB>www.java2s.com</WEB>
</PERSON>
<PERSON>
<NAME>Green</NAME>
<EMAIL>green@yourserver.com</EMAIL>
<TELEPHONE>202-414-9999</TELEPHONE>
<WEB>www.java2s.com</WEB>
</PERSON>
</PHONEBOOK>
*/
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class NameLister {
public static void main(String args[]) {
if (args.length != 1) {
System.err.PRintln("Usage: java NameLister xmlfile.xml");
System.exit(-1);
}
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
boolean name = false;
public void startElement(String uri, String localName,
String qName, Attributes attributes)
throws SAXException {
if (qName.equalsIgnoreCase("NAME")) {
name = true;
}
}
public void characters(char ch[], int start, int length)
throws SAXException {
if (name) {
System.out.println("Name: "
+ new String(ch, start, length));
name = false;
}
}
};
saxParser.parse(args[0], handler);
} catch (Exception e) {
e.printStackTrace();
}
}
}
<PHONEBOOK>
<PERSON>
<NAME>Joe Yin</NAME>
<EMAIL>joe@yourserver.com</EMAIL>
<TELEPHONE>202-999-9999</TELEPHONE>
<WEB>www.java2s.com</WEB>
</PERSON>
<PERSON>
<NAME>Karol</name>
<EMAIL>karol@yourserver.com</EMAIL>
<TELEPHONE>306-999-9999</TELEPHONE>
<WEB>www.java2s.com</WEB>
</PERSON>
<PERSON>
<NAME>Green</NAME>
<EMAIL>green@yourserver.com</EMAIL>
<TELEPHONE>202-414-9999</TELEPHONE>
<WEB>www.java2s.com</WEB>
</PERSON>
</PHONEBOOK>
*/
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class NameLister {
public static void main(String args[]) {
if (args.length != 1) {
System.err.PRintln("Usage: java NameLister xmlfile.xml");
System.exit(-1);
}
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
boolean name = false;
public void startElement(String uri, String localName,
String qName, Attributes attributes)
throws SAXException {
if (qName.equalsIgnoreCase("NAME")) {
name = true;
}
}
public void characters(char ch[], int start, int length)
throws SAXException {
if (name) {
System.out.println("Name: "
+ new String(ch, start, length));
name = false;
}
}
};
saxParser.parse(args[0], handler);
} catch (Exception e) {
e.printStackTrace();
}
}
}
更多精彩
赞助商链接