如何使用 xsd 验证 xml?

发布于 2025-01-01 02:57:42 字数 1864 浏览 1 评论 0原文

当 xml 文档包含架构时,我在根据 xml 架构验证 xml 文件时遇到问题。 xml 文件看起来像:

<?xml version="1.0"?>
<catalog xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
         xmlns:x="urn:book"> 
<!-- START OF SCHEMA -->
<xsd:schema targetNamespace="urn:book">
 <xsd:element name="book">
  <xsd:complexType>
    <xsd:sequence>
      <xsd:element name="author" type="xsd:string"/>
      <xsd:element name="title" type="xsd:string"/>
      <xsd:element name="genre" type="xsd:string"/>
      <xsd:element name="price" type="xsd:float"/>
      <xsd:element name="publish_date" type="xsd:date"/>
      <xsd:element name="description" type="xsd:string"/>
    </xsd:sequence>
    <xsd:attribute name="id" type="xsd:string"/>
  </xsd:complexType>
 </xsd:element>
</xsd:schema>
<!-- END OF SCHEMA -->
   <x:book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications with
      XML.</description>
   </x:book>
</catalog>

java 代码看起来像:

// define the type of schema - we use W3C:
String schemaLang = "http://www.w3.org/2001/XMLSchema";

// get validation driver:
SchemaFactory factory = SchemaFactory.newInstance(schemaLang);

// create schema by reading it from an XSD file:
Schema schema = factory.newSchema(new StreamSource("..........."));
Validator validator = schema.newValidator();

// at last perform validation:
validator.validate(new StreamSource("myDoc.xml"));

我的问题是在这种情况下如何使用 SchemaFactory 对象?

我很感激任何帮助!

I have problems with validating the xml file against xml schema in case when xml document contains schema. The xml file looks like:

<?xml version="1.0"?>
<catalog xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
         xmlns:x="urn:book"> 
<!-- START OF SCHEMA -->
<xsd:schema targetNamespace="urn:book">
 <xsd:element name="book">
  <xsd:complexType>
    <xsd:sequence>
      <xsd:element name="author" type="xsd:string"/>
      <xsd:element name="title" type="xsd:string"/>
      <xsd:element name="genre" type="xsd:string"/>
      <xsd:element name="price" type="xsd:float"/>
      <xsd:element name="publish_date" type="xsd:date"/>
      <xsd:element name="description" type="xsd:string"/>
    </xsd:sequence>
    <xsd:attribute name="id" type="xsd:string"/>
  </xsd:complexType>
 </xsd:element>
</xsd:schema>
<!-- END OF SCHEMA -->
   <x:book id="bk101">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications with
      XML.</description>
   </x:book>
</catalog>

java code looks like:

// define the type of schema - we use W3C:
String schemaLang = "http://www.w3.org/2001/XMLSchema";

// get validation driver:
SchemaFactory factory = SchemaFactory.newInstance(schemaLang);

// create schema by reading it from an XSD file:
Schema schema = factory.newSchema(new StreamSource("..........."));
Validator validator = schema.newValidator();

// at last perform validation:
validator.validate(new StreamSource("myDoc.xml"));

And the problem for me is how to use SchemaFactory object in this case ?

I'm greatful for any help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

相守太难 2025-01-08 02:57:42

我想这就是你想要的;该代码旨在说明,而不是说明良好的编程实践。它已经用您的 XML 进行了测试。主要假设是文档元素有两个元素,第一个是 XSD,第二个是要验证的 XML。

例如,如果将 44.95 更改为 d44.95,您将得到以下输出:

XML 无效,因为 cvc-datatype-valid.1.2.1: 'd44.95' 不是 'float' 的有效值.

否则,一切都会正常,程序会打印 XML is valid.

import java.io.*;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.validation.*;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import javax.xml.xpath.*;
import org.xml.sax.InputSource;

public class TestValidation {
    public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException {
        XPath xpath = XPathFactory.newInstance().newXPath();
        NodeList nodes = (NodeList)xpath.evaluate("/*/*", new InputSource("XmlWithEmbeddedXsd.xml"), XPathConstants.NODESET);
        SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        Validator validator = factory.newSchema(new DOMSource(nodes.item(0))).newValidator();
        try {
            validator.validate(new DOMSource(nodes.item(1)));
            System.out.println("XML is valid.");
        }
        catch (SAXException ex) {
            System.out.println("XML is not valid because " + ex.getMessage());
        }
    }
}

I assume this is what you want; the code is meant to illustrate, rather than account for good programming practices. It was tested with your XML. The main assumption is that the document element has two elements, first one the XSD, second the XML to validate.

If, for example, you change 44.95 to d44.95 you will get this output:

XML is not valid because cvc-datatype-valid.1.2.1: 'd44.95' is not a valid value for 'float'.

Otherwise, everything goes fine and the program prints XML is valid.

import java.io.*;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.validation.*;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import javax.xml.xpath.*;
import org.xml.sax.InputSource;

public class TestValidation {
    public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException {
        XPath xpath = XPathFactory.newInstance().newXPath();
        NodeList nodes = (NodeList)xpath.evaluate("/*/*", new InputSource("XmlWithEmbeddedXsd.xml"), XPathConstants.NODESET);
        SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        Validator validator = factory.newSchema(new DOMSource(nodes.item(0))).newValidator();
        try {
            validator.validate(new DOMSource(nodes.item(1)));
            System.out.println("XML is valid.");
        }
        catch (SAXException ex) {
            System.out.println("XML is not valid because " + ex.getMessage());
        }
    }
}
喜爱皱眉﹌ 2025-01-08 02:57:42

作为 Gardea 解决方案的替代方案(这很好,只是我讨厌任何涉及使用 DOM 的东西),您可以进行转换以将架构和 book 元素提取为单独的文档,然后再验证其中一个文档。我提到这一点是因为验证前转换是一种未充分利用的设计模式。

As an alternative to Gardea's solution (which is fine except that I have an aversion to anything that involves using the DOM), you could do a transformation to extract the schema and the book element as separate documents before validating one against the other. I mention this because transforming-before-validating is an underused design pattern.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文