【问题标题】:performing xml validation against xsd针对 xsd 执行 xml 验证
【发布时间】:2011-07-18 03:13:22
【问题描述】:

我将 XML 作为字符串和 XSD 作为文件,我需要使用 XSD 验证 XML。我该怎么做?

【问题讨论】:

  • 你需要一个 XML 文件而不是 String 并且你可以使用 XSD 验证 XML,有很多可用的工具,如 Jaxb 2.x、Xrces 等

标签: java xml saxparser


【解决方案1】:

您可以使用 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;
}

【讨论】:

    【解决方案2】:

    您可以为此使用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)));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-20
      • 2011-10-12
      • 1970-01-01
      • 1970-01-01
      • 2013-10-30
      • 1970-01-01
      • 2013-07-30
      相关资源
      最近更新 更多