2017年2月11日 星期六

SAXParserFactory

※xml.xml

<?xml version="1.0" encoding="UTF-8"?>
<root>top1
    top2
    <first fa="f1" fb="1f">
        first-1
        <second1 sa="s1">aaa</second1>
        <second2>bbb</second2>
        <second3>ccc</second3>
    </first>
    top3
    <first fa="f2" fb="2f">
        first-2
        <second1 sa="s2">ddd</second1>
        <second2>eee</second2>
        <second3>fff</second3>
    </first>
    top4
    <first fa="f3" fb="3f">
        first-3
        <second1 sa="s3">ggg</second1>
        <second2>hhh</second2>
        <second3>iii</second3>
    </first>
</root>






SAXParserFactory只能讀取XML,不能修改、新增

※SAXHandler.java

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
    
public class SAXHandler extends DefaultHandler {
    @Override
    public void startDocument() throws SAXException {
        System.out.println("<?xml version='1.0' encoding='UTF-8'?>");
    }
    
    @Override
    public void endDocument() throws SAXException {
        System.out.println("讀取結束");
    }
    
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        System.out.print("<");
        System.out.print(qName);
        if (attributes != null) {
            for (int i = 0; i < attributes.getLength(); i++) {
                System.out.print(" " + attributes.getQName(i) + "='" + attributes.getValue(i) + "'");
            }
        }
        System.out.print(">");
    }
    
    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        System.out.print("</");
        System.out.print(qName);
        System.out.print(">");
    }
    
    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        System.out.println(new String(ch, start, length));
    }
}

※startDocument方法只是為了方便閱讀,有可能「'」會被認為不是XML,應該改成「"」



※SAXTest.java 

import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
    
public class SAXTest {
    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        parser.parse("src/main/java/xml.xml", new SAXHandler());
    }
}




沒有留言:

張貼留言