XML 如何使用?
XML 在 Web 開發的許多方面都有應用。
XML 通常用於將資料與表示形式分離開。
XML 分離資料與表示形式
XML 不包含關於如何顯示的任何資訊。
同一份 XML 資料可以在許多不同的表示場景中使用。
因此,使用 XML,可以實現資料與表示形式的完全分離。
XML 常常是 HTML 的補充
在許多 HTML 應用中,XML 用於儲存或傳輸資料,而 HTML 則用於格式化和顯示相同的資料。
XML 分離資料與 HTML
在 HTML 中顯示資料時,不應該在資料更改時去編輯 HTML 檔案。
使用 XML,資料可以儲存在單獨的 XML 檔案中。
通過幾行 JavaScript 程式碼,您可以讀取 XML 檔案並更新任何 HTML 頁面的資料內容。
Books.xml
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="web" cover="paperback">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
在本教程的 DOM 部分,您將學到更多關於使用 XML 和 JavaScript 的知識。
交易資料
在許多不同的行業中,存在數千種 XML 格式,用於描述日常資料交易
- 股票和證券
- 金融交易
- 醫療資料
- 數學資料
- 科學測量
- 新聞資訊
- 天氣服務
示例:XML 新聞
XMLNews 是用於交換新聞和其他資訊的規範。
使用標準可以使新聞生產者和新聞消費者更容易地在不同的硬體、軟體和程式語言之間生成、接收和歸檔任何型別的新聞資訊。
一個示例 XMLNews 文件
<?xml version="1.0" encoding="UTF-8"?>
<nitf>
<head>
<title>哥倫比亞地震</title>
</head>
<body>
<headline>
<hl1>哥倫比亞地震造成 143 人死亡</hl1>
</headline>
<byline>
<bytag>作者:Jared Kotler,美聯社撰稿人</bytag>
</byline>
<dateline>
<location>哥倫比亞波哥大</location>
<date>1999 年 1 月 25 日星期一 7:28 ET</date>
</dateline>
</body>
</nitf>
示例:XML 天氣服務
來自 NOAA(美國國家海洋和大氣管理局)的 XML 國家天氣服務
<?xml version="1.0" encoding="UTF-8"?>
<current_observation>
<credit>NOAA 國家氣象局</credit>
<credit_URL>http://weather.gov/</credit_URL>
<image>
<url>http://weather.gov/images/xml_logo.gif</url>
<title>NOAA 國家氣象局</title>
<link>http://weather.gov</link>
</image>
<location>紐約/肯尼迪國際機場,紐約</location>
<station_id>KJFK</station_id>
<latitude>40.66</latitude>
<longitude>-73.78</longitude>
<observation_time_rfc822>週一,2008 年 2 月 11 日 06:51:00 -0500 EST
</observation_time_rfc822>
<weather>少雲</weather>
<temp_f>11</temp_f>
<temp_c>-12</temp_c>
<relative_humidity>36</relative_humidity>
<wind_dir>西</wind_dir>
<wind_degrees>280</wind_degrees>
<wind_mph>18.4</wind_mph>
<wind_gust_mph>29</wind_gust_mph>
<pressure_mb>1023.6</pressure_mb>
<pressure_in>30.23</pressure_in>
<dewpoint_f>-11</dewpoint_f>
<dewpoint_c>-24</dewpoint_c>
<windchill_f>-7</windchill_f>
<windchill_c>-22</windchill_c>
<visibility_mi>10.00</visibility_mi>
<icon_url_base>http://weather.gov/weather/images/fcicons/</icon_url_base>
<icon_url_name>nfew.jpg</icon_url_name>
<disclaimer_url>http://weather.gov/disclaimer.html</disclaimer_url>
<copyright_url>http://weather.gov/disclaimer.html</copyright_url>
</current_observation>