zoukankan      html  css  js  c++  java
  • 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")));
    
        }
    }
  • 相关阅读:
    lottie 动画
    .netcore 跨域问题
    数据库规范
    课程总结
    Beta版本发布
    个人作业-Alpha项目测试
    第三次作业结对编程
    第二次作业-熟悉使用工具
    第一次阅读作业
    个人作业-Alpha项目测试
  • 原文地址:https://www.cnblogs.com/erdanyang/p/10310905.html
Copyright © 2011-2022 走看看