XML Schema, XSD 與 XSLT 與 DTD 的筆記


DTD 中的符號意思,和 Regex 一樣

1
2
3
* 代表 0-N
+ 代表 1-n
? 代表 0-1

XSD 中的屬性意思

1
2
minOccurs 代表這個 element 最少會出現多少次
maxOccurs 代碼這個 element 最多會出現多少次

DTD 的舉例

- foodlist 內會有 0-N 個 food

- food 裡會有 4 個 elemnts

- element 分別的屬性 (一般用 #PCDATA 就夠了)

1
2
3
4
5
6
<!ELEMENT foodlist (food*,company)>
<!ELEMENT food (name, affix+, country, price)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT affix (#PCDATA)>
<!ELEMENT country (#PCDATA)>
<!ELEMENT price (#PCDATA)>

XSD 的舉例 (將上面例子作轉換)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="foodlist">
<xs:complexType>
<xs:sequence>
<xs:element name="food" minOccurs="0" maxOccurs="unbound">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string" minOccurs="1" maxOccurs="1"></xs:element>
<xs:element name="affix" type="xs:string" minOccurs="1" maxOccurs="unbound"></xs:element>
<xs:element name="country" type="xs:string" minOccurs="1" maxOccurs="1"></xs:element>
<xs:element name="price" type="xs:decimal" minOccurs="1" maxOccurs="1"></xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="company" type="xs:string" minOccurs="1" maxOccurs="1"></xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

XML 的對應 (上面例子)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?xml version="1.0" encoding="utf-8"?>
<foodlist>
<food>
<name>Name-1</name>
<affix>Affix-1</affix>
<affix>Affix-2</affix>
<affix>Affix-3</affix>
<country>Country-1</country>
<price>19.95</price>
</food>
<food>
<name>Name-2</name>
<affix>Affix-2</affix>
<affix>Affix-3</affix>
<affix>Affix-4</affix>
<country>Country-2</country>
<price>29.95</price>
</food>
<company>Company</company>
</foodlist>

XSLT 的應用 (上面例子)

1
2
在 <?xml version="1.0" encoding="UTF-8"?> 下面
加入 <?xml-stylesheet type="text/xsl" href="foodlist.xslt"?>

foodlist.xslt 內容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<head>
<meta charset="utf-8" />
<title>food List</title>
</head>
<body>
<h3>Food list price < 20</h3>
<xsl:for-each select="foodlist/food">
<xsl:if test="price &lt; 0">
Name:
<xsl:value-of select="name" />,
Affix:
<xsl:for-each select="affix"><xsl:value-of select="text()" /> </xsl:for-each>,
Country:
<xsl:value-of select="country" />,
price:
<xsl:value-of select="price" />
<br /><br />
</xsl:if>
</xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>