JavaでSAXを使用してxml文書解析のための便利なサンプル

Javaコード

1.javax.xml.parsersパッケージのAPI

javax.xml.parsers.SAXParser;

javax.xml.parsers.SAXParserFactory;

org.xml.sax.helpers.DefaultHandler;

2.SAXのサンプルコード

public static void main(String[] args) throws Exception {
SAXParser parse = SAXParserFactory.newInstance().newSAXParser();
File f = new File(
“D:\\startnews24Project\\tts_tuan\\src\\sax_test\\java\\com\\startnews24\\sax_test\\sax.xml");
parse.parse(f, new DefaultHandler() {
@Override
public void startDocument() throws SAXException {
System.out.println(“startDocument");
}

@Override
public void endDocument() throws SAXException {
System.out.println(“endDocument");
};

@Override
public void startElement(String uri, String localName,
String qName, Attributes attributes) throws SAXException {
System.out.println(localName);
}

@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
System.out.println(localName);
}

@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
System.out.println(new String(ch, start, length));
}
});

}

Development

Posted by arkgame