Home  >  Article  >  Backend Development  >  Detailed explanation of the basic knowledge of using XML Schema to define elements (pictures and text)

Detailed explanation of the basic knowledge of using XML Schema to define elements (pictures and text)

黄舟
黄舟Original
2017-03-28 16:36:402246browse

The new XML Schema system is about to become a W3C recommended standard, with the purpose of overcoming the limitations of DTD (see sidebar, Limitations of DTD) and providing rich grammatical structures for XML documents. This article demonstrates the flexibility of schemas and explains how to use the XML Schema system to define the most basic building blocks of XML documents - elements.

XML Schema is more powerful than DTD. To illustrate the power of the XML Schema mechanism, the following three program listings briefly compare different ways of representing elements. Listing 1 gives an XML document segment, Listing 2 declares these two elements using DTD syntax, and Listing 3 is the corresponding XML Schema syntax form. Note that the same XML syntax is used in Listing 3. Through the schema, the validation parser can check whether the element InvoiceNo is a positive integer and whether the first character of the ProductID element is a letter from A to Z, followed by six Arabic digits. In contrast, a validating parser that references a DTD can only check whether the elements are represented as strings.

Listing 1: XML document segment

123456789
J123456

Listing 2: DTD segment describing the elements in Listing 1


Listing 3: XML Schema describing the elements in Listing 1





Using namespaces in XML Schema

In this collaborative world, one person may be working with documents from multiple other groups, and different groups may want to represent their documents in different ways. data elements. Additionally, they may reference elements in a document with the same name created by different groups. How to distinguish different definitions of the same name? XML Schema uses namespaces to distinguish these definitions.

Attachment:

Limitations of DTD

(Although DTD has successfully served SGML and HTML developers for 20 years as a mechanism for describing structured information, But compared with XML Schema, it has serious limitations.

DTD requires elements to be composed of the following three components:

Text string

Text string and A mix of other child elements

A set of child elements

The DTD does not use XML syntax and provides only limited support for types and namespaces)

a given XML. Schema defines a set of new names, such as element names, type names, attribute names, and attribute group names. The definitions and declarations of these names are written in the schema. Listing 3 defines names including InvoiceNo, ProductID, and ProductCode.

We say that a name defined in a schema belongs to its target namespace. The namespace itself has a fixed but unrestricted name that must conform to URL syntax. For example, for the schema section in Listing 3, you could name the namespace: http://www.SampleStore.com/Account.

The namespace name syntax is confusing because, although it starts with http://, that URL does not point to a file containing the schema definition. In fact, the URL http://www.SampleStore.com/Account does not point to any file at all, just an assigned name.

Definitions and declarations in the schema may reference names belonging to other namespaces. In this article, we call these namespaces source namespaces. Each schema has a target namespace, but there may be multiple source namespaces. Namespace names can be quite long, but abbreviations are available in XML documents through xmlns declarations. To illustrate these concepts, we can add a little more to the example pattern in Listing 4 mentioned above.

Listing 4: Target namespace and source namespace








In the XML Schema of Listing 4, the name of targetNamespace is www.SampleStore.com/Account, which contains the names InvoiceNo, ProductID and ProductCode. The names schema , element , simpleType , pattern , string , and positive-integer belong to the source namespace www.w3.org/1999/XMLSchema , abbreviated to xsd via the xmlns declaration. There is nothing special about the alias xsd, we can choose any other name. For convenience and simplicity later in this article, we use xsd to represent the namespace www.w3.org/1999/XMLSchema and omit the qualifier xsd in some code snippets. In this example, targetNamespace occasionally serves as a source namespace because other names are defined using the name ProductCode.

Detailed explanation of the basic knowledge of using XML Schema to define elements (pictures and text)

The schema section in Listing 4 does not need to specify the location of the source schema file. For the whole "schema of schemas", http://www.w3.org/1999/XMLSchema, there is no need to specify the location because its location is well known. For the source namespace www.SampleStore.com/Account , there is also no need to specify the location since it happens to be the target namespace defined in the file. To better understand how to specify the location of a schema and use the default namespace, take a look at the extended example in Listing 5.

Listing 5: Multiple source namespaces, importing one namespace









清单 5中多了一个名称空间引用: www.PartnerStore.com/PartsCatalog 。这个名称空间不同于 targetNamespace 和标准名称空间。因此必须使用 import 声明元素引入,该元素的 schemaLocation 属性指明包含模式的文件位置。默认的名称空间是www.w3.org/1999/XMLSchema ,它的 xmlns 声明没有名字。每个非限定的名字如 schema 和 element ,都属于默认名称空间www.w3.org/1999/XMLSchema 。如果模式从一个名称空间中引用了多个名字,将其指定为默认名字空间更方便。

一个 XML 实例文档可能引用多个名称空间的元素名,这些名称空间定义在不同模式中。为了引用和简化名称空间的名字,同样要使用 xmlns 声明。我们使用 XML Schema 实例名称空间的 schemaLocation 属性指定文件的位置。要注意,该属性不同于上一个例子中 xsd 名称空间的同名属性 schemaLocation 。

清单 6:使用来自多个模式的多个名称空间的名字



123456789

图 2:清单 5 和清单 6 的名称空间

Detailed explanation of the basic knowledge of using XML Schema to define elements (pictures and text)

定义元素

定义元素就是定义元素的名字和内容模型。在 XML Schema 中,元素的内容模型由其类型定义,因此 XML 文档中实例元素的值必须符合模式中定义的类型。

类型包括简单类型和复杂类型。简单类型的值不能包含元素或属性。复杂类型可以产生在其他元素中嵌套元素的效果,或者为元素增加属性。(到目前为止本文中的例子都是用户定义的简单类型,比如 ProductCode )。XML Schema 规范也包括预定义的简单类型(请参阅侧栏 简单类型)。 派生的简单类型约束了基类型的值。比如,派生简单类型 ProductCode 的值是基类型 string 值的子集。

简单的、非嵌套的元素是简单类型

不含属性或其他元素的元素可以定义为简单类型,无论是预定义的简单类型还是用户定义的简单类型,如 string 、 integer 、 decimal 、 time 、 ProductCode 等等。

清单 7:一些元素的简单类型


带有属性的元素必须是复杂类型

现在,试着向 清单 7中的简单元素 price 增加属性 currency 。您不能这样做,因为简单类型的元素不能有属性。如果希望增加属性,您必须把 price 元素定义成复杂类型。在 清单 8的例子中,我们定义了一个 匿名类型,没有明确地命名这个复杂类型。换句话说,没有定义复杂类型 complexType 的 name 属性。

清单 8:一个复杂元素类型






嵌入其他元素的元素必须是复杂类型

在 XML 文档中,一个元素可能嵌入其他的元素。这种要求可以在 DTD 中直接表示。但 XML Schema 定义一个元素,这个元素有一个类型,而这个类型可以包含其他元素和属性的声明。 表 1给出了一个简单的例子。

表 1:DTD 和 XML Schema 中复杂数据类型的比较

XML 文档


Cool XML<Title>
<Author>Cool Guy</Author>
</Book></pre><p>DTD</p><pre class="brush:xml;toolbar:false"><Book>
<Title>Cool XML<Title>
<Author>Cool Guy</Author>
</Book></pre><p>XML Schema</p><pre class="brush:xml;toolbar:false"><Book>
<Title>Cool XML<Title>
<Author>Cool Guy</Author>
</Book>


<!ELEMENT Book (Title, Author)>
<!ELEMENT Title (#PCDATA)>
<!ELEMENT Author (#PCDATA)>

<element name='Book' type='BookType'/>
<complexType name='BookType'>
<element name='Title' type='string'/>
<element name='Author' type='string'/>
</complexType></pre><p>尽管 表 1中的 XML 代码同时满足 DTD 与 XML Schema 段,但两者之间有一个很大的区别。在 DTD 中所有的元素都是全局性的,而表中的 XML Schema 允许把 Title 和 Author 定义成局部的——只出现在元素 Book 中。为了在 XML Schema 中实现与 DTD 声明完全相同的效果,元素 Title 和 Author 必须是全局范围的,如 清单 9中所示。元素 element 的 ref 属性使您能够引用前面声明的元素。</p>
<p>清单 9:用全局简单类型定义的复杂类型</p><pre class="brush:xml;toolbar:false"><element name='Title' type='string'/>
<element name='Author' type='string'/>
<element name='Book' type='BookType'/>
<complexType name='BookType'>
<element ref='Title'/>
<element ref='Author'/>
</complexType></pre><p>在 表 1和 清单 9所示的例子中, BookType 是全局性的,可用于声明其他元素。相反, 清单 10将该类型局部地定义到元素 Book 中,而且定义成匿名元素。要注意, 表 1中的 XML 文档段与表 1、 清单 9和 清单 10中三个模式段都匹配。</p>
<p>清单 10:隐藏 BookType 作为本地类型</p><pre class="brush:xml;toolbar:false"><element name='Title' type='string'/>
<element name='Author' type='string'/>
<element name='Book'>
<complexType>
<element ref='Title'/>
<element ref='Author'/>
</complexType>
</element></pre><p>表示元素的复杂约束</p>
<p>对于表示元素内容模型的约束,XML Schema 比 DTD 提供了更大的灵活性。在最简单的层次上,像在 DTD 中那样,您可以把属性和元素声明关联起来,指明能够出现的给定元素集合序列:只能出现 1 次(1)、出现 0 次或多次(*)或者出现 1 次或多次(+)。您还可以表示 XML Schema 中的其他约束,比方说使用 element 元素的 minOccurs 和 maxOccurs 属性,以及 choice 、 group 和 all 元素。</p>
<p>清单 11:表示元素类型的约束</p><pre class="brush:xml;toolbar:false"><element name='Title' type='string'/>
<element name='Author' type='string'/>
<element name='Book'>
<complexType>
<element ref='Title' minOccurs='0'/>
<element ref='Author' maxOccurs='2'/>
</complexType>
</element></pre><p>在 清单 11中, Book 中 Title 的出现是可选的(类似 DTD 的 '?')。但是, 清单 11也说明 Book 元素中至少要有一个但不能超过两个作者。 element 的 minOccurs 和 maxOccurs 属性的默认值是 1。元素 choice 只允许它的一个子女出现在实例中。另外一个元素 all ,表示这样的约束:组中的所有子元素可以同时出现一次,或者都不出现,它们可以按任意的顺序出现。 清单 12表示 Title 和 Author 两者必须同时出现(顺序任意)在 Book 中,或者都不出现。这种约束很难在 DTD 中表示。</p>
<p>清单 12:指出必须为元素定义所有的类型</p><pre class="brush:xml;toolbar:false"><xsd:element name='Title' type='string'/>
<xsd:element name='Author' type='string'/>
<xsd:element name='Book'>
<xsd:complexType>
<xsd:all>
<xsd:element ref='Tile'/>
<xsd:element ref='Author'/>
</xsd:all>
</xsd:complexType>
</xsd:element></pre><p>更上层楼</p>
<p>我们已经讨论了在 XML Schema 中定义元素所需的最基本的概念,通过一些简单的例子使您领略到它的强大功能。还有一些更强大的机制:</p>
<p>XML Schema 对类型继承提供了广泛的支持,允许重用以前定义的结构。使用所谓的 facets,您可以派生新的类型,表示其他某个类型值的更小子集,比如通过枚举、范围或模式匹配来定义子集。在本文的例子中, ProductCode 类型就是使用模式面( pattern facet)定义的。子类型也可以向基类型增加更多的元素和属性声明。</p>
<p>有几种机制控制能否定义子类型,或者能否在具体的文档中替换为子类型。比如,有可能表示 InvoiceType ( Invoice 编号的类型)不允许子类型化,任何人都不能定义新版本的 InvoiceType 。通过规定在特定的上下文中不能用 ProductCode 类型的子类型替换,也能表达这种约束。</p>
<p>除了子类型外,还可以定义等价的类型,这样,一个类型的值可以用另一个类型代替。</p>
<p>通过声明抽象的元素或者类型,XML Schema 提供了一种强制替换机制。</p>
<p>为了方便起见,可以定义并命名属性组和元素组,从而能够在后面引用这些组达到重用的目的。</p>
<p>XML Schema 提供了三个元素—— appInfo 、 documentation 和 annotation ——为模式作注解,以方便读者( documentation )和应用程序( appInfo )。</p>
<p>基于子元素的某些属性可以表示惟一性约束。</p>
<p>可以通过 W3C 站点(请参阅 参考资料)的文档进一步研究 XML Schema,或者访问 dW XML 专区了解更多的内容。目前,XML Schema 规范已经被批准,并成为候选推荐标准(Candidate Recommendation),毫无疑问您将越来越多地用到它。</p><p>The above is the detailed content of Detailed explanation of the basic knowledge of using XML Schema to define elements (pictures and text). For more information, please follow other related articles on the PHP Chinese website!</p></div><div class="nphpQianMsg"><div class="clear"></div></div><div class="nphpQianSheng"><span>Statement:</span><div>The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn</div></div></div><div class="nphpSytBox"><span>Previous article:<a class="dBlack" title="A simple example of XML Schema" href="//m.sbmmt.com/m/faq/359267.html">A simple example of XML Schema</a></span><span>Next article:<a class="dBlack" title="A simple example of XML Schema" href="//m.sbmmt.com/m/faq/359274.html">A simple example of XML Schema</a></span></div><div class="nphpSytBox2"><div class="nphpZbktTitle"><h2>Related articles</h2><em><a href="//m.sbmmt.com/m/article.html" class="bBlack"><i>See more</i><b></b></a></em><div class="clear"></div></div><ul class="nphpXgwzList"><li><b></b><a href="//m.sbmmt.com/m/faq/348309.html" title="Using dom4j to parse xml in java (sample code)" class="aBlack">Using dom4j to parse xml in java (sample code)</a><div class="clear"></div></li><li><b></b><a href="//m.sbmmt.com/m/faq/348310.html" title="How does Java read XML files? Specific implementation" class="aBlack">How does Java read XML files? Specific implementation</a><div class="clear"></div></li><li><b></b><a href="//m.sbmmt.com/m/faq/348311.html" title="Java example code for generating and parsing XML format files and strings" class="aBlack">Java example code for generating and parsing XML format files and strings</a><div class="clear"></div></li><li><b></b><a href="//m.sbmmt.com/m/faq/348313.html" title="Solution to using sax to parse xml in java" class="aBlack">Solution to using sax to parse xml in java</a><div class="clear"></div></li><li><b></b><a href="//m.sbmmt.com/m/faq/348314.html" title="Java uses xpath to parse xml example sharing" class="aBlack">Java uses xpath to parse xml example sharing</a><div class="clear"></div></li></ul></div></div><div class="nphpFoot"><div class="nphpFootBg"><ul class="nphpFootMenu"><li><a href="//m.sbmmt.com/m/"><b class="icon1"></b><p>Home</p></a></li><li><a href="//m.sbmmt.com/m/course.html"><b class="icon2"></b><p>Course</p></a></li><li><a href="//m.sbmmt.com/m/wenda.html"><b class="icon4"></b><p>Q&A</p></a></li><li><a href="//m.sbmmt.com/m/login"><b class="icon5"></b><p>My</p></a></li><div class="clear"></div></ul></div></div><div class="nphpYouBox" style="display: none;"><div class="nphpYouBg"><div class="nphpYouTitle"><span onclick="$('.nphpYouBox').hide()"></span><a href="//m.sbmmt.com/m/"></a><div class="clear"></div></div><ul class="nphpYouList"><li><a href="//m.sbmmt.com/m/"><b class="icon1"></b><span>Home</span><div class="clear"></div></a></li><li><a href="//m.sbmmt.com/m/course.html"><b class="icon2"></b><span>Course</span><div class="clear"></div></a></li><li><a href="//m.sbmmt.com/m/article.html"><b class="icon3"></b><span>Article</span><div class="clear"></div></a></li><li><a href="//m.sbmmt.com/m/wenda.html"><b class="icon4"></b><span>Q&A</span><div class="clear"></div></a></li><li><a href="//m.sbmmt.com/m/dic.html"><b class="icon6"></b><span>Dictionary</span><div class="clear"></div></a></li><li><a href="//m.sbmmt.com/m/course/type/99.html"><b class="icon7"></b><span>Manual</span><div class="clear"></div></a></li><li><a href="//m.sbmmt.com/m/xiazai/"><b class="icon8"></b><span>Download</span><div class="clear"></div></a></li><li><a href="//m.sbmmt.com/m/faq/zt" title="Topic"><b class="icon12"></b><span>Topic</span><div class="clear"></div></a></li><div class="clear"></div></ul></div></div><div class="nphpDing" style="display: none;"><div class="nphpDinglogo"><a href="//m.sbmmt.com/m/"></a></div><div class="nphpNavIn1"><div class="swiper-container nphpNavSwiper1"><div class="swiper-wrapper"><div class="swiper-slide"><a href="//m.sbmmt.com/m/" >Home</a></div><div class="swiper-slide"><a href="//m.sbmmt.com/m/article.html" class="hover">Article</a></div><div class="swiper-slide"><a href="//m.sbmmt.com/m/wenda.html" >Q&A</a></div><div class="swiper-slide"><a href="//m.sbmmt.com/m/course.html" >Course</a></div><div class="swiper-slide"><a href="//m.sbmmt.com/m/faq/zt" >Topic</a></div><div class="swiper-slide"><a href="//m.sbmmt.com/m/xiazai"  >Download</a></div><div class="swiper-slide"><a href="//m.sbmmt.com/m/game" >Game</a></div><div class="swiper-slide"><a href="//m.sbmmt.com/m/dic.html" >Dictionary</a></div><div class="clear"></div></div></div><div class="langadivs"  ><a href="javascript:;" class="bg4 bglanguage"></a><div class="langadiv" ><a  onclick="javascript:setlang('zh-cn');" class="language course-right-orders chooselan "  href="javascript:;"><span>简体中文</span><span>(ZH-CN)</span></a><a  onclick="javascript:;" class="language course-right-orders chooselan chooselanguage"  href="javascript:;"><span>English</span><span>(EN)</span></a><a  onclick="javascript:setlang('zh-tw');" class="language course-right-orders chooselan "  href="javascript:;"><span>繁体中文</span><span>(ZH-TW)</span></a><a  onclick="javascript:setlang('ja');" class="language course-right-orders chooselan "  href="javascript:;"><span>日本語</span><span>(JA)</span></a><a  onclick="javascript:setlang('ko');" class="language course-right-orders chooselan "  href="javascript:;"><span>한국어</span><span>(KO)</span></a></div></div><script>            var swiper = new Swiper('.nphpNavSwiper1', {
                slidesPerView : 'auto',
                observer: true,//修改swiper自己或子元素时,自动初始化swiper
                observeParents: true,//修改swiper的父元素时,自动初始化swiper

            });
        </script></div></div><!--顶部导航 end--><script>isLogin = 0;</script><script type="text/javascript" src="/static/layui/layui.js"></script><script type="text/javascript" src="/static/js/global.js?4.9.47"></script></div><script src="https://vdse.bdstatic.com//search-video.v1.min.js"></script><link rel='stylesheet' id='_main-css' href='/static/css/viewer.min.css' type='text/css' media='all'/><script type='text/javascript' src='/static/js/viewer.min.js?1'></script><script type='text/javascript' src='/static/js/jquery-viewer.min.js'></script><script>jQuery.fn.wait = function (func, times, interval) {
    var _times = times || -1, //100次
    _interval = interval || 20, //20毫秒每次
    _self = this,
    _selector = this.selector, //选择器
    _iIntervalID; //定时器id
    if( this.length ){ //如果已经获取到了,就直接执行函数
        func && func.call(this);
    } else {
        _iIntervalID = setInterval(function() {
            if(!_times) { //是0就退出
                clearInterval(_iIntervalID);
            }
            _times <= 0 || _times--; //如果是正数就 --

            _self = $(_selector); //再次选择
            if( _self.length ) { //判断是否取到
                func && func.call(_self);
                clearInterval(_iIntervalID);
            }
        }, _interval);
    }
    return this;
}
$("table.syntaxhighlighter").wait(function() {
    $('table.syntaxhighlighter').append("<p class='cnblogs_code_footer'><span class='cnblogs_code_footer_icon'></span></p>");
});
$(document).on("click", ".cnblogs_code_footer",function(){
      $(this).parents('table.syntaxhighlighter').css('display','inline-table');$(this).hide();
});
$('.nphpQianCont').viewer({navbar:true,title:false,toolbar:false,movable:false,viewed:function(){$('img').click(function(){$('.viewer-close').trigger('click');});}});
</script></body></html>