根据xml架构验证xml文件 [英] validate xml file against xml schema

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

问题描述

这是关于针对XML模式验证XML文件(例如:marshalledfile.xml)(例如:schemafile.xsd)。我们使用jaxb将java对象编组到一个xml文件中。

this is about validating a XML file (eg: marshalledfile.xml) against a XML schema (eg: schemafile.xsd). we are using jaxb to marshall java objects into into a xml file.


  1. 最好的方法是什么?

  1. what is the best way to do it ?

有人能给出一个如何做的简单示例吗?

can someone give a simple example of how to do it ?

感谢您的帮助。

谢谢,
Alo

Thanks, Alo

推荐答案

您可以直接在Marshaller中设置Schema。首先,您需要创建一个Schema实例(javax.xml.validation包):

You can set the Schema directly in the Marshaller. First, you need to create a Schema instance (javax.xml.validation package):

SchemaFactory factory = SchemaFactory.newInstance(
            XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(new StreamSource(new File("schema1.xsd")));

现在您已拥有Schema,只需将Marshaller中的属性设置为
即可验证生成的XML:

Now that you have the Schema, just set the property in the Marshaller to validate the generated XML:

MovieLibrary library = ...; // <-- your JAXB-annotated tree

JAXBContext ctx = JAXBContext.newInstance(MovieLibrary.class);
Marshaller marshaller = ctx.createMarshaller();
marshaller.setSchema(schema);
marshaller.marshal(new JAXBElement<MovieLibrary>(new QName("movieLibrary"), 
                                                    MovieLibrary.class, library),
                   new FileOutputStream("/tmp/library.xml"));

另请参阅如何根据XML架构验证输入?在 Jarfiller JAXB指南中。

See also "How to Validate Input against an XML Schema?" in the Jarfiller JAXB Guide.

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

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