XML Schema全接触

ZDNet软件频道 时间:2001-08-14 作者:zdnet china |  我要评论()
本文关键词:
本文将介绍XML定义语言、XML Schema全貌和XML Schema如何校验XML文档。

由了XML Schema,你可以用来校验XML文档的语义和结构。在MSXML 4.0技术预览版本已经提供了用XSD Schema来校验XML文档的功能。在校验文档时,将schema添加到XMLSchemaCache对象中,设置其 object, set the schemas property of a DOMDocument对象的schemas属性引用XMLSchemaCache对象中的schema。在将XML文档载入到DOMDocument对象中时将自动执行校验操作。我们不妨用例子来说明如何在Visual Basic中通过编程实现XML文档校验。其中包括:

books.xsd
用来校验books.xml文件的Schema
books.xml
该文件将被载入并且和books.xsd对照校验
Visual Basic校验代码
创建一个XMLSchemaCache对象,将schema添加给它,然后设置schemas property of the DOMDocument对象的shemas属性。在开始的时候你要进行如下操作:
  1. 打开Visual Basic 6.0,选择Standard EXE新项目
  2. 在Project菜单中选择References.
  3. 在Available References列表中选择Microsoft XML,v4.0
  4. 给Form1添加一个Command button
  5. 存储该项目

books.xml

在XML编辑器甚至一般的文本编辑器中输入以下XML代码,并且存为books.xml:

< ?xml version="1.0"?>
<
x:catalog xmlns:x="urn:books">
<
book id="bk101">
<
author>Gambardella, Matthew</< font>author>
< title>XML Developer's Guide</< font>title>
< genre>Computer</< font>genre>
< price>44.95</< font>price>
< publish_date>2000-10-01</< font>publish_date>
< description>An in-depth look at creating applications with XML.</< font>description>
< title>2000-10-01</< font>title>
</< font>book>
</< font>x:catalog>

books.xsd

下面是本例中使用的books.xsd schema。

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<
xsd:element name="catalog" type="CatalogData"/>
<
xsd:complexType name="CatalogData">
<
xsd:sequence>
<
xsd:element name="book" type="bookdata" minOccurs="0" maxOccurs="unbounded"/>
</< font>xsd:sequence>
</< font>xsd:complexType>
< xsd:complexType name="bookdata">
< 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"/>
</< font>xsd:sequence>
< xsd:attribute name="id" type="xsd:string"/>
</< font></xsd:complexType>
</< font></xsd:schema>

Visual Basic校验代码

你可以运行下面的例子:

  1. 拷贝下面的代码到Command1_Click过程中

    Private Sub Command1_Click()
    Dim xmlschema As MSXML2.XMLSchemaCache
    Set xmlschema = New MSXML2.XMLSchemaCache
    xmlschema.Add "urn:books", App.Path & "ooks.xsd"
    Dim xmldom As MSXML2.DOMDocument
    Set xmldom = New MSXML2.DOMDocument
    Set xmldom.schemas = xmlschema

    xmldom.async = False
    xmldom.Load App.Path & "ooks.xml"

    If xmldom.parseError.errorCode <> 0 Then
    MsgBox xmldom.parseError.errorCode & " " & xmldom.parseError.reason
    Else
    MsgBox "No Error"
    End If
    End Sub

  2. 执行该程序,然后点击Command1按钮,将返回"No Errors"消息框

百度大联盟认证黄金会员Copyright© 1997- CNET Networks 版权所有。 ZDNet 是CNET Networks公司注册服务商标。
中华人民共和国电信与信息服务业务经营许可证编号:京ICP证010391号 京ICP备09041801号-159
京公网安备:1101082134