[XML entry series] Chapter 2 DTD and schema technology

Source: Internet
Author: User
[XML entry series] Chapter 2 DTD and schema technology -- v512 studio Editor: Xuan Yu
DTD   Schema   Cpoyright
Element Built-in DTD Introduction Application Example My blog
Attribute External DTD Verify Similarities and differences with DTD V512 Studio
Entity Namespace End description Data Communication Protection Chinese Emy of Sciences

DTD (document type definition)
Defines the structure of the XML file and provides syntax and rules for the XML file. The content can be defined either in the XML file or outside the XML file.
XML file composition: All XML files are composed of the following modules: elements, attributes, entities, pcdata (text content), CDATA
Industries or organizations that use XML for data exchange can define their own DTD. DTD is optional for XML.
To exchange data correctly, the structure of the XML file needs to be determined.
Example: <student>
<Name> Liu Wei </Name>
<Number> 2966556 </number>
</Student>
Here, a <student> tag can only contain one <Name> and one <number> tag.
In this case, you need to use a syntax file to restrict the tags in XML, the order in which tags appear, and the number of occurrences. Then you can use the DTD

XML built-in DTD content
<? XML version = "1.0" encoding = "UTF-8"?>
<! Doctype book list [
<! Element book list (computer books) *>
<! Element computer books (title, price)>
<! Element name (# pcdata)>
<! Element price (# pcdata)>
]>
<Book list>
<Computer books>
<Title> the present and present of XML </title>
<Price> 66.66 </price>
</Computer books>
</Book list>

External DTD (the content of DTD and XML are in different files respectively)
DTD file book. DTD:
<? XML version = "1.0" encoding = "UTF-8"?>
<! Element book list (computer books) *>
<! Element computer books (title, price)>
<! Element name (# pcdata)>
<! Element price (# pcdata)>
XML files using external DTD files:
<? XML version = "1.0" encoding = "UTF-8"?>
<! Doctype book list system "book. DTD">
The DTD defined separately in each XML document can be promoted to a public DTD shared in a system.
The keyword system is used to reference the common DTD used in many XML documents written by an author or organization.
Another external DTD, a dtd developed by an authority and provided for specific industries or the public. The keyword is public.
For example: Web. XML must comply with the specific DTD; otherwise, the web. the order of the tags in XML will be disrupted, So errors will be reported when Tomcat is started, and these orders will be written in the following DTD
<! Doctype web-app public "-// Sun Microsystems, Inc. // DTD web application 2.3 //" http://java.sun.com/dtd/web-app_2_3.dtd ">
Supplement: In DTD: <! Element computer books (title, price)>
In XML: <title> current and present of XML </title> <price> 66.66 </price>
Display: The title is displayed in XML order and the price is displayed.
If XML is used: <price> 66.66 </price>
<Title> the present and present of XML </title>
Display: The price is displayed in XML order and the title is displayed.
Note: although the book name and price in XML are inconsistent with those in DTD, ie still displays XML content as is.
This is because IE can only check whether the XML file is well-formed, and does not verify the matching between XML and the corresponding DTD.
If you want to verify whether the XML complies with the DTD, you can write a program to verify the compliance. The Code is as follows:
Package com. v512;
Import javax. xml. parsers. documentbuilder;
Import javax. xml. parsers. documentbuilderfactory;
Import org. xml. Sax. inputsource;
Public class validatedtd {
Public static void main (string [] ARGs ){
Try {documentbuilderfactory DBF = documentbuilderfactory. newinstance ();
// Documentbuilderfactory: a document construction factory that can be used to parse and verify XML.
DBF. setvalidating (true); // whether to perform syntax verification or DTD verification on the current XML file
Documentbuilder builder = DBF. newdocumentbuilder ();
Builder. parse (New inputsource ("xml-2-2.xml "));
} Catch (exception e) {e. printstacktrace ();}}}
Then introduce the corresponding XML and DTD files to this project: copy the XML and DTD files together, right-click the project name in eclipse and select Paste
Run this program: Right-click the validatedtd. Java in eclipse and choose run as → Java application Alt + Shift + X, J
If the XML file conforms to the DTD syntax, the red error message is not displayed.
If the XML does not conform to the DTD syntax, a red error message is displayed. You only need to find the following error prompt information.

DTD-Element
Syntax: <! Element name Category> or <! Element element name (element content)>
Example: <! Element name (# pcdata)>
<! Element computer books (titles, prices)>: the sequence of child elements in XML must appear strictly in the Order stated by its DTD.
Empty elements are declared using the keyword empty: <! Element element name empty>
Example: In DTD: <! Element BR empty> in XML: <br/>
Element with any content: <! Element element name any>
Example: In DTD: <! Element student any> in XML: <student> Liu Wei </student> or <student> <Name> Liu Wei </Name> </student> are legal.
Elements that appear only once: <! Element element name (child element name)>
Example: <! Element book list (computer books)>
Declare the element that appears at least once: <! Element element name (child element name +)>
Example: <! Element book list (computer books +)>
Declare zero or multiple elements: <! Element element name (child element name *)>
Example: <! Element book list (computer books *)>
Element with zero or one declaration: <! Element element name (child element name?)>
Example: <! Element book list (computer books?)>
Statement or: <! Element element name (child element name | child element name 2)>
Example: <! Element book list (computer books | literature books)>
Declare hybrid content: <! Element child element name (# pcdata | child element name) *>
Example: <! Element book list (# pcdata | computer books) *>

Character Description
+ Appears once or multiple times
* Zero or multiple occurrences
? Optional. It does not appear or appears once.
() A group of expressions to be matched together
| Or (OR)
' And (and), the requirements must strictly follow the order requirements

For more information, see the following table:

① Sub-elements require Sequence
In DTD: <! Element computer books (title, price)>
<! Element name (# pcdata)>
<! Element price (# pcdata)>
XML: <computer books>
<Title> J2EE tutorial </title>
<Price> 100 </price>
</Computer books>
③ Repeated Element
In DTD: <! Element computer books (title, author +)>
<! Element name (# pcdata)>
<! Element author (# pcdata)>
XML: <computer books>
<Title> J2EE tutorial </title>
<Author> Zhang San </author>
<Author> Li Si </author>
</Computer books>
② Subelements do not require order
In DTD: <! Element computer books (Title | price) *>
<! Element name (# pcdata)>
<! Element price (# pcdata)>
XML: <computer books>
<Title> J2EE tutorial </title>
<Price> 100 </price>
</Computer books>
④ Group Elements
In DTD: <! Element computer books (title, price) +>
<! Element name (# pcdata)>
<! Element price (# pcdata)>
XML: <computer books>
<Title> J2EE tutorial </title>
<Price> 100 </price>
<Title> XML tutorial </title>
<Price> 50 </price>
</Computer books>

DTD-attribute (attributes are declared through ATTLIST)
Syntax: <! ATTLIST element name attribute type default value>
Example: In DTD: <! ATTLIST payment type CDATA "cash">
In XML: <payment type = "cash"/> the read type value is cash.
<Payment type = "check"/> the read type value is check.
<Payment/> the read type value is cash.
Attribute type (commonly used: CDATA, (EN1 | EN2 |...), ID)

Type Description
CDATA Character data)
(EN1 | EN2 | ..) This value is a value in the enumeration list.
ID The value is a unique ID.
Idref The value is the ID of another element.
Idrefs List of other IDS
Nmtoken The value is a valid XML name.
Nmtokens List of valid XML names
Entity The value is an entity.
Entities The value is an object list.
Notation This value is the name of the symbol.
XML: The value is a predefined XML value.

Default Attribute Value

Value Default Attribute Value
Value Default Attribute Value
# Required Attribute values are required
# Implied Property is not required
# Fixed value The property value is fixed.

# Required Syntax: <! ATTLIST element name attribute type # required>
Example: In DTD: <! ATTLIST payment type CDATA # required>
In XML: <payment type = "cash"/> is acceptable
<Payment/> NO.
# Implied Syntax: <! ATTLIST element name attribute type # implied>
Example: In DTD: <! ATTLIST payment type CDATA # implied>
In XML: <payment type = "cash"/> is acceptable
<Payment/> Yes
# Fixed syntax: <! ATTLIST element name attribute type # fixed "value">
Example: In DTD: <! ATTLIST payment type CDATA # fixed "cash">
In XML: <payment type = "cash"/> is acceptable
<Payment/> Yes

DTD-entity (entity is a variable used to define shortcuts that reference common text or special characters)
Similar to the function we usually use, we can first define a function, and then use this function through its name, so the entity is like this.
Object Reference is a reference to an object. An object can be declared either internally or externally (it can be defined in the current DTD or another DTD)
Syntax for internal entity Declaration: <! Entity Object Name "object Value">
Example: In DTD: <! Entity writer "Bill Gates">
<! Entity copyright "Copyright jobedu.com.cn">
XML: <author> & writer; & Copyright; </author>
Syntax for external entity Declaration: <! Entity Object Name System "uri/url">
Example: In DTD: <! Entity writer System "http://www.jobedu.com.cn/dtd/person.dtd">
In XML: <author> & writer; </author>

Namespace
If an XML document contains elements described by multiple DTD, a name conflict may occur.
In order to solve the name conflict issue, the W3C XML Team has developed the namespace standard.
Namespaces allocate different spaces to them, and then use the prefix identification method to solve the conflict problem.
Prefix Identification: adds an identifier before the element name and attribute name to uniquely identify the DTD from which the current element or attribute comes.
For details, see the following example:
<Contact: Contact List xmlns: Contact = "Contact List. DTD" xmlns: Enterprise Manager = "Enterprise Manager. DTD">
<Contact: Contact> <! -- Use xmlns to introduce two. DTD namespaces and name them as contacts and business managers respectively -->
<Contact: Name> Zhang San </contact: Name>
<Contact: Id> 001 </contact: Id>
<Contact Person: Company> Company A </Contact Person: Company>
<Contact: email> liu@ddd.com </contact: email>
<Contact: Phone number> (010) 82637089 </contact: Phone number>
<Contact: Address>
<Contact: Sub-district> No. 1234, wujie </contact: Sub-district>
<Contact Person: City> Beijing </Contact Person: City>
</Contact: Address>
<Contact: immediate superior>
<Company manager: Name> Wang Wu </company manager: Name>
<Business manager: Phone number>
<Company manager: Secretary phone number> (010) 82632266 </company manager: Secretary phone number>
<Business manager: Mobile Phone> 13601231111 </Business Manager: Mobile Phone>
</Business Manager: Phone number>
</Contact: immediate superior>
</Contact: Contact>
</Contact: Contact List>
If the namespace is written as xmlns = "Contact List. DTD", it indicates that all the elements not prefixed by "Enterprise Manager" Use the namespace "Contact List. DTD" by default.

Schema describes the structure of an XML document, also known as XML schema definition (XSD). It is more powerful than DTD.
DTD has a major drawback: it is not an XML file, so it cannot process the DTD in a unified way.
Schema is very similar to DTD. It is an XML file, so it is very unified in processing.
Schema is an XML-based DTD substitution. For example, the default spring configuration file applicationcontext. xml
Before spring2.0, the syntax defined in this configuration file is DTD.
However, in later versions, including the latest spring2.5, the syntax defined in this configuration file is schema.
Because schema can define more information than DTD

Similarities and differences between Schema and DTD
Schema is the successor of DTD and will replace DTD in the future. It uses XML syntax
There are many advantages to writing a schema by using XML: you do not have to learn new syntaxes. You can use an XML editor to parse and edit schema files.
Schema advantages: schema can be expanded to meet future needs. Better schema and more powerful functions. Schema is written based on XML. Schema supports data types // description
Schema is extensible (exponential data structure and content) because they are written in XML
Through an extensible schema definition, you can: reuse your schema in other Schemas
Create your own data types derived from standard types
Reference multiple schemas in the same document. That is, multiple known or existing schema files can be referenced in an XML file.
Note: DTD lacks some definitions of data types.
Supporting data types is a key factor for defining XML syntax. It is of great significance for us to write XML or XML applications.
Because we often use XML files to transmit data or let it carry data. During data transmission or carrying, we must define whether the data structure conforms to a certain degree.
For example, some content I want to pass is a string, and I want to define its String Length range.
This is almost impossible to define such a data type in DTD, but it is very easy and convenient to implement in schema.

Schema protects Data Communication
Through schema, the sender can describe data in a way that the receiver can understand
When data is sent from the sender to the receiver, the key point is that both parties should have the same "expectation" for the content. // Add ①
A data type, such as "03-11-2004", is interpreted as January 1, November 3 in some countries, and is considered as January 1, March 11 in other countries. // supplement ②
However, an XML Element with data types, such as <date type = "date"> </date> can ensure consistent understanding of the content. // Add ③
Supplement ①: This expected data value should satisfy certain data structures. This is not easy to define in DTD or the data structure defined in DTD is very limited, so schema is very flexible.
Supplement ②: for example, transfer a date data in XML: "03-11-2004 ". If the format of this date is in the DTD or when there is no appointment, it is very easy to misunderstand as may November 3 or may March 11.
③: If the transmitted XML file is defined in schema, it will be easily differentiated. Because it can be forced to define its type as the date type and the format required by date is "YYYY-MM-DD"

Schema application example (the schema file extension is. XSD)
Email. XSD content
<? XML version = "1.0"?> // Declare it as an XML file
<Xs: schema xmlns: xs = "http://www.w3.org/2001/XMLSchema">
<Xs: element name = "email"> // defines an element named email.
<Xs: complextype> // indicate that the email contains sub-elements, such as to, from, and title.
<Xs: sequence> // sequence indicates that child elements must appear in strict order.
<Xs: element name = "to" type = "XS: string"/>
<Xs: element name = "from" type = "XS: string"/>
<Xs: element name = "title" type = "XS: string"/>
<Xs: element name = "body" type = "XS: string"/>
<Xs: element name = "date" type = "XS: Date"/>
</Xs: sequence> // The XML to be used in this schema requires an email element and five child elements.
</Xs: Element> // In the schema, element indicates the definition element, and complextype indicates that it is a composite element.
</Xs: schema> // The namespace is used. Prefix is XS, value is http://www.w3.org/2001/XMLSchema
XML file using schema
<? XML version = "1.0" encoding = "UTF-8"?>
<Email xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi: nonamespaceschemalocation = "email. XSD">
<To> liuwei8809@163.com </to>
<From> hellokitty@163.com </from>
<Title> loving </title> <! -- If this row is switched to the next row, an error is returned because the sequence of child elements is strictly specified in the schema used in the XML. -->
<Body> I love you forever! </Body>
<Date> 2008-02-03 </date> <! -- If it is changed to, an error is returned because the date type is less than 15 months. -->
</Email>
Schema File explanation
<? XML version = "1.0"?>
<Xs: schema>
...
...
</Xs: schema>
<Schema> an element is the root element of a schema file.
Xmlns: xs = http://www.w3.org/2001/XMLSchema
Displays the elements and data types used in the schema from the namespace "http://www.w3.org/2001/XMLSchema"
It also specifies that elements and data types from namespaces "http://www.w3.org/2001/XMLSchema" should use the prefix XS

Verify that XML meets the schema
IE cannot verify whether the XML meets the schema. It can only check whether the XML format is good. To verify the XML format, it can only be implemented through proprietary tool software or API programming.
Create schema file: Right-click the project and select XML Schema under new
Create an XML file: Right-click the project and select XML (Advanced templates) under new (select XML (Basic templates) to create a basic template)
Eclipse formatting: Right-click the code and select format (CTRL + Shift + F) under source to format and indent the code.
With eclipse, You can edit the schemaxml file and check whether the XML complies with the schema rules.

Schema description
This chapter briefly introduces the schema.
In fact, the schema content is not as simple as described here.
It is actually very complex, especially it has a wide range of data types and a wide range of forms of definition.
Recommended to everyone a free Tutorial: http://www.w3school.com.cn here are text tutorials, no video tutorials

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.