【问题标题】:How to validate in Java a XML with XSD schema如何在 Java 中使用 XSD 模式验证 XML
【发布时间】:2010-02-19 18:37:11
【问题描述】:

在给定 XSD Schema 的情况下,如何在 Java 中验证 XML?

【问题讨论】:

    标签: java xml validation


    【解决方案1】:

    尝试以下方法:

    File schemaFile = new File("schema.xsd");
    File xmlFile = new File("input.xml");
    Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(schemaFile);
    Validator validator = schema.newValidator();
    validator.validate(new StreamSource(new FileInputStream(xmlFile)));
    

    【讨论】:

      【解决方案2】:

      有许多示例说明如何通过快速搜索来做到这一点。这是来自Java Ranch 的一个使用 JaxP 的:

      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      factory.setValidating(true);
      
      factory.setAttribute(
            "http://java.sun.com/xml/jaxp/properties/schemaLanguage", 
            "http://www.w3.org/2001/XMLSchema");
      factory.setAttribute(
        "http://java.sun.com/xml/jaxp/properties/schemaSource",
        "http://domain.com/mynamespace/mySchema.xsd");
      Document doc = null;
      try{        
           DocumentBuilder parser = factory.newDocumentBuilder();
           doc = parser.parse("data.xml");
         }
      catch (ParserConfigurationException e){
           System.out.println("Parser not configured: " + e.getMessage());
         }
      catch (SAXException e){
           System.out.print("Parsing XML failed due to a " + e.getClass().getName() + ":");
           System.out.println(e.getMessage());
         }
      catch (IOException e){
           e.printStackTrace();
         }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-09
        • 2011-02-19
        • 1970-01-01
        • 2023-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多