格式正確的XML文件表示該文件符合XML規範中所有格式相關的條件限制。然而,何謂有效合法的XML文件呢?引用XML規範中的定義,即為「如果XML文件由 文件類別宣告 (Document Type Declaration,DTD)加以定義,並且遵從DTD所定義的規則來表現和限制資料,則該XML文件則為有效合法的文件」。您將會在本章的後續討論中學到這些相關知識。
獨立文件宣告使用的屬性值可以為 yes 或 no 。屬性值使用 yes 會指示剖析器所有相關於文件的資訊都已經包含在文件中了,這表示文件中沒有指定外部的實體(entity),也沒有使用外部的架構(external schema)來指定文件中的預設屬性值;屬性值使用 no 會指示應用程式需要取得文件以外的資訊以完成文件剖析。
<?xml version="1.0"?>
<Joke author="Groucho Marx">
<Setup>Outside of a dog, a book is man's best
friend.</Setup>
<Punchline>Inside of a dog, it's too dark to
read.</Punchline>
</Joke>
請注意範例中的XML宣告,以及每一個開始標籤都有相對應的結束標籤。
有效合法的XML文件
假設您要提供格式正確的XML文件來形容您最喜歡的笑話-您提供了兩份文件,一份短的和一份長的文件。
<?xml version="1.0"?>
<favorite-joke author="Pate">
<one-liner>A duck walks into a bar and says to the
bartender, "Gimme a shot of whisky and put it on
my bill."</one-liner>
</favorite-joke>
長的笑話比第一個笑話更複雜。
<?xml version="1.0"?>
<duck_joke>
<scene number="1">
A duck walks into a bar, goes up to the bartender,
and says, "Don't you have any grapes?" The
bartender says, "No, this is a bar, of course
we don't have any grapes."
</sence>
<scene number="2">
The next day, the duck walks into a bar, goes
up to the bartender, and says, "Don't you have any
grapes?" The bartender says, "No, like I told
you yesterday, we don't have any grapes."
If you come in here one more time asking for
grapes, I'm going to nail your webbed feet to
that bar!"
</scene>
<scene number="3">
The next day, the duck walks into a bar, goes
up to the bartender, and says, "Don't you have any
nails?" The bartender says, "No, this is a bar,
of course we don't have any nails." Then the
duck says, "Don't you have any grapes?"
</sence>
</duck_joke>
<?xml version="1.0"?>
<!DOCTYPE Joke SYSTEM "Joke.dtd">
<Joke author="Groucho Marx">
<Setup>Outside of a dog, a book is man's
best friend</Setup>
<Punchline>Inside of a dog, it's too dark
to read.</Punchline>
</Joke>
您可以看看清單4-1中所舉的發票範例,因為該發票是用於書,所以在 invoice 元素的 body 元素中有一個元素 tilte 。然而,在包含地址部分的架構中,也有一個元素名稱為 title ,該元素的意義是表示歡迎訂購該書的讀者(MS., Mr., Dr.等等),此時就出現了兩個 title 元素,卻有分別不同的意義。我們想要使用不同的方式處理它們,此時就是使用名稱空間的時機。
請注意清單4-2的根元素 invoice 中包含了名稱空間屬性,並且其子元素 address 中也包含了自身的名稱空間資訊。如果您檢查 xmlns 中所指的文件,您會發現在 invoice 名稱空間中定義了如 number 、 customer 、 date 元素的資訊等等;如果您檢查 address 的名稱空間,您會發現如 street 、 city 、 state 和 zipcode 等資訊。
當您宣告名稱空間的時候,在父層範圍中的子元素會變成名稱空間的一部份。這稱為預設的名稱空間(default namespace)。但是如果您想要在一個元素範圍內混合名稱空間時要怎麼做呢?舉例來說,如果您想要讓 invoice 元素中的 date 元素有不同的資料型別宣告要怎麼辦?
請注意次要名稱空間的描述在第3行,該宣告指定您可以在 invoice 元素範圍中的任何地方使用該名稱空間,但是您必須在欲宣告元素的開始標籤和屬性中明確地指定該名稱空間。在第6行 date 元素的屬性使用 dt 名稱空間,本範例中,在 datatype 架構中的 type 屬性設定為 date 。請注意 dt 名稱空間也用於 body 元素屬性的14-16行中。
W3C XML Schema Working Group依然不斷致力於XML Schema的語法,2000年4月,公佈了Working Drafts of XML Schema Parts 1、2和3。XML Schema提供了XML 1.0 DTDs特性的超集合(superset),BizTalk率先使用XDR為描述XML文件的語法。