根据XSD文件验证XML文件的最佳方法是什么? [英] What's the best way to validate an XML file against an XSD file?

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

问题描述

我正在生成一些需要符合给我的xsd文件的xml文件。什么是验证它们是否符合的最佳方法?

I'm generating some xml files that needs to conform to an xsd file that was given to me. What's the best way to verify they conform?

推荐答案

Java运行时库支持验证。上次我检查过这是封面上的Apache Xerces解析器。您应该使用 javax.xml。 validation.Validator

The Java runtime library supports validation. Last time I checked this was the Apache Xerces parser under the covers. You should probably use a javax.xml.validation.Validator.

import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.*;
import java.net.URL;
import org.xml.sax.SAXException;
//import java.io.File; // if you use File
import java.io.IOException;
...
URL schemaFile = new URL("http://host:port/filename.xsd");
// webapp example xsd: 
// URL schemaFile = new URL("http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd");
// local file example:
// File schemaFile = new File("/location/to/localfile.xsd"); // etc.
Source xmlFile = new StreamSource(new File("web.xml"));
SchemaFactory schemaFactory = SchemaFactory
    .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
try {
  Schema schema = schemaFactory.newSchema(schemaFile);
  Validator validator = schema.newValidator();
  validator.validate(xmlFile);
  System.out.println(xmlFile.getSystemId() + " is valid");
} catch (SAXException e) {
  System.out.println(xmlFile.getSystemId() + " is NOT valid reason:" + e);
} catch (IOException e) {}

架构工厂常量是字符串 http://www.w3.org/2001/XMLSchema 定义了XSD。上面的代码根据URL http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd 验证WAR部署描述符,但你可以像轻松验证本地文件。

The schema factory constant is the string http://www.w3.org/2001/XMLSchema which defines XSDs. The above code validates a WAR deployment descriptor against the URL http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd but you could just as easily validate against a local file.

您不应使用DOMParser来验证文档(除非您的目标是创建文档对象模型)。这将在解析文档时开始创建DOM对象 - 如果您不打算使用它们会浪费。

You should not use the DOMParser to validate a document (unless your goal is to create a document object model anyway). This will start creating DOM objects as it parses the document - wasteful if you aren't going to use them.

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

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