如何在Java中使用XSD模式验证XML

如何在Java中使用XSD模式验证XML,java,xml,validation,Java,Xml,Validation,在给定XSD模式的情况下,如何在Java中验证XML?请尝试以下操作: 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.newV

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

请尝试以下操作:

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)));
请尝试以下操作:

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)));

关于如何通过快速搜索实现这一点,有许多示例。下面是一个使用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();
   }

关于如何通过快速搜索实现这一点,有许多示例。下面是一个使用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();
   }