Java 什么';根据XSD文件验证XML文件的最佳方法是什么?
我正在生成一些xml文件,这些文件需要符合提供给我的xsd文件。验证其符合性的最佳方法是什么?以下是如何使用。这方面的教程(要求注册) 原始属性:公然抄袭自:Java 什么';根据XSD文件验证XML文件的最佳方法是什么?,java,xml,validation,xsd,Java,Xml,Validation,Xsd,我正在生成一些xml文件,这些文件需要符合提供给我的xsd文件。验证其符合性的最佳方法是什么?以下是如何使用。这方面的教程(要求注册) 原始属性:公然抄袭自: 你在找工具还是图书馆 就库而言,事实上的标准是同时具有和版本 不过,请注意,这是一个非常重要的解决方案。但是,再次强调,根据XSD文件验证XML是一个相当重要的问题 至于为您提供的工具,这似乎是一个不错的免费软件解决方案,但我不能确定您是否亲自使用过它。Java运行时库支持验证。上次我检查这是ApacheXerces解析器的封面下。你可能
你在找工具还是图书馆 就库而言,事实上的标准是同时具有和版本 不过,请注意,这是一个非常重要的解决方案。但是,再次强调,根据XSD文件验证XML是一个相当重要的问题
至于为您提供的工具,这似乎是一个不错的免费软件解决方案,但我不能确定您是否亲自使用过它。Java运行时库支持验证。上次我检查这是ApacheXerces解析器的封面下。你可能应该使用一个 架构工厂常量是字符串
http://www.w3.org/2001/XMLSchema
它定义了XSD。上面的代码根据URL验证WAR部署描述符http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd
但您也可以轻松地根据本地文件进行验证
您不应该使用DOMParser来验证文档(除非您的目标是创建文档对象模型)。这将在解析文档时开始创建DOM对象——如果您不打算使用它们,这将是一种浪费。我只需要根据XSD验证XML一次,所以我尝试了XMLFox。我觉得这很令人困惑和奇怪。帮助说明似乎与界面不匹配
我最终使用了LiquidXMLStudio 2008(v6),它更易于使用,也更为人所熟悉(UI与我经常使用的VisualBasic2008Express非常相似)。缺点:免费版本中没有验证功能,因此我不得不使用30天试用版。如果您是通过编程生成XML文件,您可能需要查看库。使用命令行工具,XMLBeans将基于XSD自动生成和打包一组Java对象。然后可以使用这些对象基于此模式构建XML文档 它内置了对模式验证的支持,可以将Java对象转换为XML文档,反之亦然
还有一些Java库的用途与XMLBeans类似。还有一个答案:既然您说需要验证正在生成的文件(写入),那么您可能希望在写入时验证内容,而不是先写入,然后再读回以进行验证。如果使用基于SAX的编写器,您可能可以使用JDKAPI进行Xml验证:如果是这样,只需通过调用“validator.validate(source,result)”链接到验证器中,其中源代码来自编写器,结果是输出需要的地方
或者,如果您使用Stax来编写内容(或者使用或可以使用Stax的库),那么您也可以在使用XMLStreamWriter时直接支持验证。下面是一个演示如何完成的示例:我们使用ant构建项目,因此可以使用schemavalidate任务检查配置文件:
<schemavalidate>
<fileset dir="${configdir}" includes="**/*.xml" />
</schemavalidate>
现在顽皮的配置文件将使我们的构建失败
如果你有一台Linux机器,你可以使用免费的命令行工具SAXCount。我觉得这很有用
SAXCount -f -s -n my.xml
它根据dtd和xsd进行验证。
50MB的文件需要5s
在debian挤压中,它位于包“libxerces-c-samples”中
dtd和xsd的定义必须在xml中!您不能单独配置它们。使用Java 7,您可以按照中提供的文档进行操作
由于这是一个流行的问题,我将指出java还可以针对“引用的”xsd进行验证,例如,如果.xml文件本身使用
xsi:schemaLocation
或xsi:noNamespaceSchemaLocation
(或特定名称空间的xsi)在头中指定xsd:
这适用于多个名称空间等。
这种方法的问题在于,xmlsns:xsi
可能是一个网络位置,因此默认情况下,它会在每次验证时都出现在网络上,但并不总是最优的
下面是一个根据任何XSD的it引用验证XML文件的示例(即使必须从网络中提取):
通过手动指定XSD(请参见此处的一些其他答案)或使用“xml目录”,可以避免从网络中提取引用的XSD,即使xml文件引用url。Spring显然也支持URL请求,以便为本地文件提供验证服务。或者您也可以通过设置自己的,例如:
另请参见以获取其他教程
我相信默认情况下是使用DOM解析,您可以使用SAX解析器执行类似的操作,即验证
saxReader.setEntityResolver(这里是您的解析器)代码>使用JAXB,您可以使用以下代码:
@Test
public void testCheckXmlIsValidAgainstSchema() {
logger.info("Validating an XML file against the latest schema...");
MyValidationEventCollector vec = new MyValidationEventCollector();
validateXmlAgainstSchema(vec, inputXmlFileName, inputXmlSchemaName, inputXmlRootClass);
assertThat(vec.getValidationErrors().isEmpty(), is(expectedValidationResult));
}
private void validateXmlAgainstSchema(final MyValidationEventCollector vec, final String xmlFileName, final String xsdSchemaName, final Class<?> rootClass) {
try (InputStream xmlFileIs = Thread.currentThread().getContextClassLoader().getResourceAsStream(xmlFileName);) {
final JAXBContext jContext = JAXBContext.newInstance(rootClass);
// Unmarshal the data from InputStream
final Unmarshaller unmarshaller = jContext.createUnmarshaller();
final SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
final InputStream schemaAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(xsdSchemaName);
unmarshaller.setSchema(sf.newSchema(new StreamSource(schemaAsStream)));
unmarshaller.setEventHandler(vec);
unmarshaller.unmarshal(new StreamSource(xmlFileIs), rootClass).getValue(); // The Document class is the root object in the XML file you want to validate
for (String validationError : vec.getValidationErrors()) {
logger.trace(validationError);
}
} catch (final Exception e) {
logger.error("The validation of the XML file " + xmlFileName + " failed: ", e);
}
}
class MyValidationEventCollector implements ValidationEventHandler {
private final List<String> validationErrors;
public MyValidationEventCollector() {
validationErrors = new ArrayList<>();
}
public List<String> getValidationErrors() {
return Collections.unmodifiableList(validationErrors);
}
@Override
public boolean handleEvent(final ValidationEvent event) {
String pattern = "line {0}, column {1}, error message {2}";
String errorMessage = MessageFormat.format(pattern, event.getLocator().getLineNumber(), event.getLocator().getColumnNumber(),
event.getMessage());
if (event.getSeverity() == ValidationEvent.FATAL_ERROR) {
validationErrors.add(errorMessage);
}
return true; // you collect the validation errors in a List and handle them later
}
}
@测试
public void testCheckXmlIsValidAgainstSchema(){
info(“根据最新模式验证XML文件…”);
MyValidationEventCollector vec=新的MyValidationEventCollector();
validateXmlAgainstSchema(vec、inputXmlFileName、inputXmlSchemaName、inputXmlRootClass);
断言(vec.getValidationErrors().isEmpty())为(expectedValidationResult));
}
私有void validateXmlAgainstSchema(最终MyValidationEventCollector vec、最终字符串xmlFileName、最终字符串xsdSchemaName、最终类rootClass){
try(InputStream xmlFileIs=Thread.currentThread().getContextClassLoader().getResourceAsStream(xmlFileName);){
final JAXBContext jContext=JAXBContext.newInstance(rootClass);
//从InputStream解组数据
final Unmarshaller Unmarshaller=jContext.createUnmarshaller();
final SchemaFactory sf=SchemaFactory.newInstance(xmlstants.W3C\u XML\u SCHEMA\u NS\u URI);
final InputStream schemaAsStream=Thread.currentThread().getContextClassLoader().getResourceAs
SAXCount -f -s -n my.xml
// create a SchemaFactory capable of understanding WXS schemas
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
// load a WXS schema, represented by a Schema instance
Source schemaFile = new StreamSource(new File("mySchema.xsd"));
Schema schema = factory.newSchema(schemaFile);
// create a Validator instance, which can be used to validate an instance document
Validator validator = schema.newValidator();
// validate the DOM tree
try {
validator.validate(new StreamSource(new File("instance.xml"));
} catch (SAXException e) {
// instance document is invalid!
}
<document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://www.example.com/document.xsd">
...
<document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.example.com/my_namespace http://www.example.com/document.xsd">
...
SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
Schema schema = factory.newSchema();
public static void verifyValidatesInternalXsd(String filename) throws Exception {
InputStream xmlStream = new new FileInputStream(filename);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
factory.setNamespaceAware(true);
factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
"http://www.w3.org/2001/XMLSchema");
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(new RaiseOnErrorHandler());
builder.parse(new InputSource(xmlStream));
xmlStream.close();
}
public static class RaiseOnErrorHandler implements ErrorHandler {
public void warning(SAXParseException e) throws SAXException {
throw new RuntimeException(e);
}
public void error(SAXParseException e) throws SAXException {
throw new RuntimeException(e);
}
public void fatalError(SAXParseException e) throws SAXException {
throw new RuntimeException(e);
}
}
Source xmlFile = new StreamSource(xmlFileLocation);
SchemaFactory schemaFactory = SchemaFactory
.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema();
Validator validator = schema.newValidator();
validator.setResourceResolver(new LSResourceResolver() {
@Override
public LSInput resolveResource(String type, String namespaceURI,
String publicId, String systemId, String baseURI) {
InputSource is = new InputSource(
getClass().getResourceAsStream(
"some_local_file_in_the_jar.xsd"));
// or lookup by URI, etc...
return new Input(is); // for class Input see
// https://stackoverflow.com/a/2342859/32453
}
});
validator.validate(xmlFile);
@Test
public void testCheckXmlIsValidAgainstSchema() {
logger.info("Validating an XML file against the latest schema...");
MyValidationEventCollector vec = new MyValidationEventCollector();
validateXmlAgainstSchema(vec, inputXmlFileName, inputXmlSchemaName, inputXmlRootClass);
assertThat(vec.getValidationErrors().isEmpty(), is(expectedValidationResult));
}
private void validateXmlAgainstSchema(final MyValidationEventCollector vec, final String xmlFileName, final String xsdSchemaName, final Class<?> rootClass) {
try (InputStream xmlFileIs = Thread.currentThread().getContextClassLoader().getResourceAsStream(xmlFileName);) {
final JAXBContext jContext = JAXBContext.newInstance(rootClass);
// Unmarshal the data from InputStream
final Unmarshaller unmarshaller = jContext.createUnmarshaller();
final SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
final InputStream schemaAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(xsdSchemaName);
unmarshaller.setSchema(sf.newSchema(new StreamSource(schemaAsStream)));
unmarshaller.setEventHandler(vec);
unmarshaller.unmarshal(new StreamSource(xmlFileIs), rootClass).getValue(); // The Document class is the root object in the XML file you want to validate
for (String validationError : vec.getValidationErrors()) {
logger.trace(validationError);
}
} catch (final Exception e) {
logger.error("The validation of the XML file " + xmlFileName + " failed: ", e);
}
}
class MyValidationEventCollector implements ValidationEventHandler {
private final List<String> validationErrors;
public MyValidationEventCollector() {
validationErrors = new ArrayList<>();
}
public List<String> getValidationErrors() {
return Collections.unmodifiableList(validationErrors);
}
@Override
public boolean handleEvent(final ValidationEvent event) {
String pattern = "line {0}, column {1}, error message {2}";
String errorMessage = MessageFormat.format(pattern, event.getLocator().getLineNumber(), event.getLocator().getColumnNumber(),
event.getMessage());
if (event.getSeverity() == ValidationEvent.FATAL_ERROR) {
validationErrors.add(errorMessage);
}
return true; // you collect the validation errors in a List and handle them later
}
}
Source xmlFile = new StreamSource(Thread.currentThread().getContextClassLoader().getResourceAsStream("your.xml"));
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(Thread.currentThread().getContextClassLoader().getResource("your.xsd"));
Validator validator = schema.newValidator();
validator.validate(xmlFile);
// create the XSD schema from your schema file
XMLValidationSchemaFactory schemaFactory = XMLValidationSchemaFactory.newInstance(XMLValidationSchema.SCHEMA_ID_W3C_SCHEMA);
XMLValidationSchema validationSchema = schemaFactory.createSchema(schemaInputStream);
// create the XML reader for your XML file
WstxInputFactory inputFactory = new WstxInputFactory();
XMLStreamReader2 xmlReader = (XMLStreamReader2) inputFactory.createXMLStreamReader(xmlInputStream);
try {
// configure the reader to validate against the schema
xmlReader.validateAgainst(validationSchema);
// parse the XML
while (xmlReader.hasNext()) {
xmlReader.next();
}
// no exceptions, the XML is valid
} catch (XMLStreamException e) {
// exceptions, the XML is not valid
} finally {
xmlReader.close();
}