xml解析之 sax、dom4j解析

/**
 * sax 解析xml文档指定标签的值
 */
public class Demo4 {

    public static void main(String[] args) throws ParserConfigurationException,
            SAXException, IOException {
        // 1、创建解析工厂
        SAXParserFactory factory = SAXParserFactory.newInstance();
        // 2、得到解析器
        SAXParser sp = factory.newSAXParser();
        // 3、得到读取器
        XMLReader reader = sp.getXMLReader();
        // 4、设置内容处理器
        reader.setContentHandler(new TagValueHandler());
        // 5、读取xml内容
        reader.parse("src/book.xml");
    }

}

// 获取指定标签的值
class TagValueHandler extends DefaultHandler {

    private String currentTag;// 记住当前分析到的是什么标签
    private int needNumber = 2;// 想获取第几个标签的值
    private int currentNumber;// 当前解析到第几个

    @Override
    public void startElement(String uri,
                             String localName,
                             String qName,
                             Attributes attributes) throws SAXException {
        currentTag = qName;
        if("作者".equals(currentTag)){
            currentNumber++;
        }
    }

    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        if ("作者".equals(currentTag)&&currentNumber==needNumber) {
            System.out.println(new String(ch, start, length));
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        currentTag = null;
    }

}

dom4j

/**
 * dom4j解析xml
 */
public class Demo5 {

    // 得到第二本书的 <书名 name="xxxxx">javaScript</书名>
    @Test
    public void read() throws Exception {
        SAXReader reader = new SAXReader();
        Document document = reader.read(new File("src/book.xml"));
        Element root = document.getRootElement();
        Element book = (Element) root.elements("书").get(1);
        String value = book.element("书名").getText();
        System.out.println(value);
    }

    // 得到第二本书的 <书名 name="xxxxx">javaScript</书名> name的属性值
    @Test
    public void readAttr() throws Exception {
        SAXReader reader = new SAXReader();
        Document document = reader.read(new File("src/book.xml"));
        Element root = document.getRootElement();
        Element book = (Element) root.elements("书").get(1);
        // String value = book.element("书名").attribute("name").getValue();
        String value = book.element("书名").attributeValue("name");
        System.out.println(value);
    }

    // 在第一本书添加一个售价
    @Test
    public void add() throws Exception {
        SAXReader reader = new SAXReader();
        Document document = reader.read(new File("src/book.xml"));
        Element book = document.getRootElement().element("书");
        book.addElement("售价").addText("209元");
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("gb2312");
        XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream("src/book.xml"),
                                                                "gb2312"),
                                         format);
        writer.write(document);
        writer.close();
    }

    // 在第一本书指定位置添加一个售价 更改List集合的顺序
    @Test
    public void add2() throws Exception {
        SAXReader reader = new SAXReader();
        Document document = reader.read(new File("src/book.xml"));
        Element book = document.getRootElement().element("书");
        List list = book.elements();
        Element price = DocumentHelper.createElement("售价");
        price.setText("209元");
        list.add(2, price);

        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("gb2312");
        XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream("src/book.xml"),
                                                                "gb2312"),
                                         format);
        writer.write(document);
        writer.close();
    }

    @Test
    public void delete() throws Exception {
        SAXReader reader = new SAXReader();
        Document document = reader.read(new File("src/book.xml"));

        Element price = document.getRootElement().element("书").element("售价");
        price.getParent().remove(price);

        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("gb2312");
        XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream("src/book.xml"),
                                                                "gb2312"),
                                         format);
        writer.write(document);
        writer.close();
    }

    @Test
    public void update() throws Exception {
        SAXReader reader = new SAXReader();
        Document document = reader.read(new File("src/book.xml"));

        Element book = (Element) document.getRootElement().elements("书").get(1);
        book.element("作者").setText("活立木");
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("gb2312");
        XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream("src/book.xml"),
                                                                "gb2312"),
                                         format);
        writer.write(document);
        writer.close();
    }
}


你可能感兴趣的:(xml解析之 sax、dom4j解析)