2011-03-18 109 views
5

我有XML作为字符串和XSD作为文件,我需要使用XSD验证XML。我怎样才能做到这一点?对xsd执行xml验证

+0

要么u需要一个XML文件中的字符串代替,比你可以验证与XSD的XML,有很多可用工具如JAXB 2.x中,Xrces等 – 2011-03-18 12:19:04

回答

1

您可以使用javax.xml.validation的API这样的:

String xml = "<root/>"; // XML as String 
File xsd = new File("schema.xsd"); // XSD as File 

SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 
Schema schema = sf.newSchema(xsd); 

SAXParserFactory spf = SAXParserFactory.newInstance(); 
spf.setSchema(schema); 
SAXParser sp = spf.newSAXParser(); 
XMLReader xr = sp.getXMLReader(); 
xr.parse(new InputSource(new StringReader(xml))); 
9

可以使用的javax.xml.validation API来做到这一点。

public boolean validate(String inputXml, String schemaLocation) 
    throws SAXException, IOException { 
    // build the schema 
    SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); 
    File schemaFile = new File(schemaLocation); 
    Schema schema = factory.newSchema(schemaFile); 
    Validator validator = schema.newValidator(); 

    // create a source from a string 
    Source source = new StreamSource(new StringReader(inputXml)); 

    // check input 
    boolean isValid = true; 
    try { 

    validator.validate(source); 
    } 
    catch (SAXException e) { 

    System.err.println("Not valid"); 
    isValid = false; 
    } 

    return isValid; 
} 
+0

适合我的用途 - 谢谢 – thonnor 2017-01-20 23:28:37