元素是 XML 的積分單位。它可擴展、彼此有關聯,命名規則也很簡單。這一節把這三件事講清楚。
先看一份最基本的便條文件:
<note> <to>Tove</to> <from>Jani</from> <body>Don't forget me this weekend!</body> </note>
假設我們寫了一支程式,從 XML 中取出 to、from、body 三個元素,輸出成:
MESSAGE To: Tove From: Jani Don't forget me this weekend!
現在,文件作者又補進了一些額外資訊:
<note> <date>1999-08-01</date> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>
程式會壞掉嗎?不會。它仍然能找到那三個元素,輸出完全相同的結果。
這就是可擴展性的實際意義:新增元素不會破壞既有消費方,因為雙方並未透過固定位置耦合,而是透過名稱查找。這也是 XML 適合長期演進的資料格式的重要原因。
要讀懂 XML 的術語,必須理解元素之間的關係是類比家族結構的。
以下用一本書的結構描述來說明:
Book Title: My First XML Chapter 1: Introduction to XML What is HTML What is XML Chapter 2: XML Syntax Elements must have a closing tag Elements must be correctly nested
對應的 XML 文件:
<book>
<title>My First XML</title>
<prod id="33-657" media="paper"></prod>
<chapter>Introduction to XML
<para>What is HTML</para>
<para>What is XML</para>
</chapter>
<chapter>XML Syntax
<para>Elements must have a closing tag</para>
<para>Elements must be properly nested</para>
</chapter>
</book>
book 是根元素。title 與 chapter 是 book 的子元素;反過來說,book 是它們的父元素。title 與 chapter 互為兄弟元素(或姊妹元素),因為它們有相同的父元素。para 是各個 chapter 的子元素,同時彼此互為兄弟。這套親子兄弟的說法並非只是比喻。後面學 XPath 時,你會直接寫出 /book/chapter/para 這樣的路徑,用到正是這層結構關係;而 XSLT 的樣板比對、DOM 的節點走訪,也全建立在這組術語之上。
XML 元素的命名限制很少,主要是:
實務建議:名稱要具描述性,用底線分隔單字(如 <first_name>、<last_name>)比用連字號或點號安全——因為 first-name 可能被誤解為減法運算,first.name 可能被誤解為屬性存取。名稱長度沒有硬限制,但求簡潔,<book_title> 勝過 <the_title_of_the_book>。
另外,名稱中不能用冒號,那是保留給名稱空間(namespace)使用的分隔符。