根据XSD验证XML [英] Validating XML against XSD

查看:95
本文介绍了根据XSD验证XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to validate an XML file with a given XSD file. I simply need the method to return true if the validation went fine or false otherwise.

推荐答案

返回简单的真或假(也是你不需要任何外部库):

Returns simply true or false (also you don't need any external library):

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

这篇关于根据XSD验证XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆