根据模式验证 XML 文档 [英] validating a XML document against a schema

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

问题描述

我需要一些代码示例来展示如何根据架构验证 xml 文件...

I need some code sample which shows how i can validate a xml file against a schema...

下面是我的 XML 文档..a.xml"

Below is say my XML document.. "a.xml"

一月211983年

说我要验证上述 xml 的架构如下,名为XMLValidationSchema.xsd"

Say the schema against which i want to validate the above xml is as below named "XMLValidationSchema.xsd"


现在有人可以帮我编写 java 代码,将这些作为输入并给出正确的输出,就像 XML 文档是否是我指定的架构中的有效文档一样...

Now can some one help me write the java code that will take these as input and give proper output like if the XML doc is a valid doc as per the schema i specified...

谢谢...

推荐答案

一个使用 JAXP 的简单示例:

A simple example using JAXP:

import java.io.File;
import java.io.IOException;

import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.xml.sax.SAXException;

public class XMLValidator {
    public void validateXML(final String schemaPath, final String xmlToValidatePath) throws SAXException, IOException {

        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Source schemaSource = new StreamSource(new File(schemaPath));
        Schema schema = schemaFactory.newSchema(schemaSource);

        Validator validator = schema.newValidator();
        validator.validate(new StreamSource(xmlToValidatePath));
    }
}

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

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