用sax解析xml
2012年07月10日
⁄ 综合
⁄ 共 3452字 ⁄ 字号
小 中 大
- package net.risesoft.common.util;
- import org.xml.sax.*;
- import javax.xml.parsers.*;
- import org.xml.sax.helpers.DefaultHandler;
- import java.io.*;
- public class SaxParse {
- public static void main(String argv[]) {
- SaxParse saxParserApp = new SaxParse();
-
- }
- public boolean parseDocument(InputStream is) {
- boolean flag=false;
- try {
- SAXParserFactory factory = SAXParserFactory.newInstance();
- SAXParser saxParser = factory.newSAXParser();
- DefaultHandler handler = new CustomSAXHandler();
- saxParser.parse(is, handler);
- CustomSAXHandler h = (CustomSAXHandler) handler;
- flag=h.getResult();
- } catch (SAXException e) {
- } catch (ParserConfigurationException e) {
- } catch (IOException e) {
- }
- return flag;
- }
- private class CustomSAXHandler extends DefaultHandler {
- private boolean flag;
- private boolean result;
- private StringBuffer content=new StringBuffer();
- public boolean getResult(){
- return result;
- }
- private String filename = null;
- private byte[] fileContent = null;
- public CustomSAXHandler() {
- }
- public void startDocument() throws SAXException {
- System.out.println("Event Type: Start Document");
- }
- public void endDocument() throws SAXException {
- result=true;
- System.out.println("Event Type: End Document");
- }
- public void startElement(String uri, String localName, String qName,
- Attributes attributes) throws SAXException {
- if ("IMGNAME".equalsIgnoreCase(qName)) {
- flag = true;
- }
- }
- public void endElement(String uri, String localName, String qName)
- throws SAXException {
- if ("IMGNAME".equalsIgnoreCase(qName))
- flag = false;
- if ("IMGVALUE".equalsIgnoreCase(qName)) {
- try {
- String value=content.toString();
- fileContent = AdapterUtil.base64Decode(value);
- if (filename != null && fileContent != null) {
- File file = new File("e://" + filename);
- if (!file.exists())
- file.createNewFile();
- OutputStream fos = new FileOutputStream(file);
- fos.write(fileContent);
- fos.close();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- filename = null;
- fileContent = null;
- content=new StringBuffer();
- }
- }
- public void characters(char[] ch, int start, int length)
- throws SAXException {
- String str = new String(ch, start, length).trim();
- if (flag)
- filename = str;
- else
- content.append(str);
- }
- public void error(SAXParseException e) throws SAXException {
- System.out.println("Error: " + e.getMessage());
- }
- public void fatalError(SAXParseException e) throws SAXException {
- System.out.println("Fatal Error: " + e.getMessage());
- }
- public void warning(SAXParseException e) throws SAXException {
- System.out.println("Warning: " + e.getMessage());
- }
- }
- }