根据XSD验证XML

时间:2011-07-25 11:45:12

标签: java xml validation xsd

我需要使用给定的XSD文件验证XML文件。如果验证失败,我只需要该方法返回true。否则。

4 个答案:

答案 0 :(得分:65)

返回true或false(也不需要任何外部库):

static boolean validateAgainstXSD(InputStream xml, InputStream xsd)
{
    try
    {
        SchemaFactory factory = 
            SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema(new StreamSource(xsd));
        Validator validator = schema.newValidator();
        validator.validate(new StreamSource(xml));
        return true;
    }
    catch(Exception ex)
    {
        return false;
    }
}

答案 1 :(得分:3)

public boolean validate() {
  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");
    return true;
  } catch (Exception e) {
    return false;
  }
}

答案 2 :(得分:3)

这可能取决于您使用的库,但在Google上搜索“如何在java中验证xml文件”给了我这些结果,您可能会找到答案:

first interesting result

second interesting result

答案 3 :(得分:2)

XMLUnit有一些很好的类来做这个,在他们的README文件中有一个例子:

skin = new Skin(Gdx.files.internal("uiskin.json"), new  TextureAtlas(Gdx.files.internal("uiskin.atlas")));
相关问题