XML Tree Structure

XML 文件形成了一種樹結構,它從“根”開始,然後擴展到“葉”。

XML Tree Structure

DOM Node Tree

XML 文件實例

上圖代表這個 XML 中的書單:

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="美食">
  <title lang="zh">雅舍談吃</title>
  <author>梁實秋</author>
  <press>江蘇文藝出版社</press>
  <year>2013</year>
  <price>35</price>
  <ISBN>9787539962771</ISBN>
</book>
<book category="兒童">
  <title lang="zh">了不起的狐狸爸爸</title>
  <author>羅爾德·達爾</author>
  <translator>代維</translator>
  <press>明天出版社</press>
  <year>2009</year>
  <price>10</price>
  <ISBN>9787533259563</ISBN>
</book>
<book category="文學">
  <title lang="zh">將熟悉變為陌生</title>
  <author>齊格蒙·鲍曼</author>
  <author>彼得·哈夫納</author>
  <translator>王立秋</translator>
  <press>南京大學出版社</press>
  <year>2023</year>
  <price>68</price>
  <ISBN>9787305269387</ISBN>
</book>
<book category="科学">
  <title lang="zh">你想要飛翔嗎,像鳥一樣?</title>
  <author>理查德·道金斯</author>
  <author>亚娜·伦佐娃</author>
  <translator>高天羽</translator>
  <press>湖南科学技术出版社</press>
  <year>2023</year>
  <price>88</price>
  <ISBN>9787571019075</ISBN>
</book>
<book category="政治" cover="平装">
  <title lang="zh">Tungkol sa Demokrasiya ng Amerika</title>
  <author>托克维尔</author>
  <translator>董果良</translator>
  <press>商务印书馆</press>
  <year>1989</year>
  <price>60</price>
  <ISBN>9787100124553</ISBN>
</book>
</bookstore>

XML Tree Structure

XML 文档中的元素形成了一棵元素树

这棵树从根元素开始,并扩展到树的子元素

XML 文档必须包含根元素。该元素是所有其他元素的父元素。

所有元素都可以有子元素:

<root>
  <child>
    <subchild>.....</subchild>
  </child>
</root>

父、子以及同胞等术语用于描述元素之间的关系。

父元素拥有子元素。子元素也有父元素。相同层级上的子元素成为同胞(兄弟或姐妹)。

所有元素均可拥有文本内容(雅舍谈吃)和属性(category="美食"),类似 HTML 中那样。

自描述的语法

XML 使用简单的具有自我描述性的语法:

<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>George</to>
<from>John</from>
<heading>Paalaala</heading>
<body>Don't forget the meeting!</body>
</note>

第一行是 XML 声明。它定义 XML 的版本 (1.0) 和所使用的编码 (ISO-8859-1 = Latin-1/西欧字符集)。

下一行描述文档的根元素(像在说:“本文档是一个便签”):

<note>

接下来 4 行描述根的 4 个子元素(to, from, heading 以及 body):

<to>George</to>
<from>John</from>
<heading>Paalaala</heading>
<body>Don't forget the meeting!</body>

The last line defines the end of the root element:

</note>

From this example, it can be assumed that the XML document contains a note from John to George.

XML has excellent self-descriptive properties, do you agree?