XML的学习

一、用jaxp(java自带)实现xml的解析与校验:

package org.eclipse.winery.repository;

import java.io.File;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;

import org.w3c.dom.Document;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

/**
 * Hello world!
 *
 */
public class App {
    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);// 让解析器支持命名空间
        factory.setValidating(true);// 设置解析器在解析文档的时候校验文档
        SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        URL resource = App.class.getResource("/web-app_3_1.xsd");
        Schema schema;
        schema = schemaFactory.newSchema(resource);
        factory.setSchema(schema);// 使用具体的xsd进行校验
        DocumentBuilder db = factory.newDocumentBuilder();
        db.setErrorHandler(new ErrorHandler() {

            @Override
            public void warning(SAXParseException exception) throws SAXException {
                // TODO Auto-generated method stub
                System.out.println("warning" + exception.getMessage());
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
                // TODO Auto-generated method stub
                System.out.println("fatalError" + exception.getMessage());
            }

            @Override
            public void error(SAXParseException exception) throws SAXException {
                // TODO Auto-generated method stub
                System.out.println("error" + exception.getMessage());
            }
        });// 添加ErrorHandler,将解析的异常手动抛出
        Document doc = db.parse(App.class.getResourceAsStream("/web.xml"));
        TransformerFactory tff = TransformerFactory.newInstance();
        Transformer tf = tff.newTransformer();
        tf.setOutputProperty(OutputKeys.INDENT, "yes");//输出换行
        tf.transform(new DOMSource(doc), new StreamResult(new File("result.xml")));

    }
}

 

posted @ 2019-01-23 19:29  海平面下的我们  阅读(124)  评论(0编辑  收藏  举报