XSD - 语法
XML XSD 保存在单独的文档中,然后可以将该文档链接到 XML 文档来使用它。
句法
XSD 的基本语法如下 -
<?xml version = "1.0"?>
<xs:schema xmlns:xs = "http://www.w3.org/2001/XMLSchema">
targetNamespace = "http://www.tutorialspoint.com"
xmlns = "http://www.tutorialspoint.com" elementFormDefault = "qualified">
<xs:element name = 'class'>
<xs:complexType>
<xs:sequence>
<xs:element name = 'student' type = 'StudentType' minOccurs = '0'
maxOccurs = 'unbounded' />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name = "StudentType">
<xs:sequence>
<xs:element name = "firstname" type = "xs:string"/>
<xs:element name = "lastname" type = "xs:string"/>
<xs:element name = "nickname" type = "xs:string"/>
<xs:element name = "marks" type = "xs:positiveInteger"/>
</xs:sequence>
<xs:attribute name = 'rollno' type = 'xs:positiveInteger'/>
</xs:complexType>
</xs:schema>
<架构> 元素
Schema 是 XSD 的根元素,并且始终是必需的。
<xs:schema xmlns:xs = "http://www.w3.org/2001/XMLSchema">
上面的片段指定模式中使用的元素和数据类型在http://www.w3.org/2001/XMLSchema命名空间中定义,并且这些元素/数据类型应以xs为前缀。它始终是必需的。
targetNamespace = "http://www.tutorialspoint.com"
上面的片段指定此架构中使用的元素是在http://www.tutorialspoint.com命名空间中定义的。它是可选的。
xmlns = "http://www.tutorialspoint.com"
上面的片段指定默认命名空间是http://www.tutorialspoint.com。
elementFormDefault = "qualified"
上面的片段表明在此模式中声明的任何元素在任何 XML 文档中使用它们之前都必须经过命名空间限定。它是可选的。
引用模式
看看下面的参考架构 -
<?xml version = "1.0"?>
<class xmlns = "http://www.tutorialspoint.com"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.tutorialspoint.com student.xsd">
<student rollno = "393">
<firstname>Dinkar</firstname>
<lastname>Kad</lastname>
<nickname>Dinkar</nickname>
<marks>85</marks>
</student>
<student rollno = "493">
<firstname>Vaneet</firstname>
<lastname>Gupta</lastname>
<nickname>Vinni</nickname>
<marks>95</marks>
</student>
<student rollno = "593">
<firstname>Jasvir</firstname>
<lastname>Singh</lastname>
<nickname>Jazz</nickname>
<marks>90</marks>
</student>
</class>
xmlns = "http://www.tutorialspoint.com"
上面的片段指定了默认名称空间声明。模式验证器使用此命名空间来检查所有元素是否属于此命名空间。它是可选的。
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://www.tutorialspoint.com student.xsd">
定义 XMLSchema-instance xsi 后,使用schemaLocation属性。该属性有两个值:命名空间和 XML 模式的位置,使用时用空格分隔。它是可选的。