XML คืออะไร (ตอนที่ 4)

เนื่องจาก XML ไม่มีการกำหนดชื่อของ element ที่ตายตัว จึงอาจเกิดปัญหาในการตั้งชื่อซ้ำกัน แต่วัตุถประสงค์และองค์ประกอบไม่ตรงกัน ยกตัวอย่างเช่น

<table>
  <tr>
      <td>Apples</td>
      <td>Bananas</td>
  </tr>
</table>

เอกสารที่จัดรูปแบบเป็นตารางข้อมูล

<table>
  <name>African Coffee Table</name>
  <width>80</width>
  <length>120</length>
</table>

และเอกสารที่จัดเก็บข้อมูลเฟอร์นิเจอร์

จะเห็นว่าทั้ง 2 ส่วนจะมี root element เป็น table เหมือนกัน แต่ table แรก และ table หลังมีข้อมูลที่ไม่เหมือนกัน วิธีการแก้ปัญหาดังกล่าวทำได้โดยเพิ่ม Prefix เข้าไปในชื่อ ดังนี้

<h:table>
  <h:tr>
      <h:td>Apples</h:td>
      <h:td>Bananas</h:td>
  </h:tr>
</h:table>

เอกสารที่จัดรูปแบบเป็นตารางข้อมูล

<f:table>
  <f:name>African Coffee Table</f:name>
  <f:width>80</f:width>
  <f:length>120</f:length>
</f:table>

เอกสารที่จัดเก็บข้อมูลเฟอร์นิเจอร์

สำหรับเอกสาร XML จะมี attribute เพิ่มเติมอีกส่วนหนึ่งเพื่อเป็นการประกาศ namespace สำหรับอ้างอิงภายหลัง ดังนี้

<table xmlns="http://www.w3.org/TR/html4/ ">
  <tr>
      <td>Apples</td>
      <td>Bananas</td>
  </tr>
</table>

เอกสารที่จัดรูปแบบเป็นตารางข้อมูล

<table xmlns="http://www.w3schools.com/furniture ">
  <name>African Coffee Table</name>
  <width>80</width>
  <length>120</length>
</table>

เอกสารที่จัดเก็บข้อมูลเฟอร์นิเจอร์

ตัวอย่างการอ้างอิงโดยใช้ namespace

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform ">
<xsl:template match="/">
<html>
<body>
    <h2>My CD Collection</h2>
    <table border="1">
     <tr>
      <th align="left">Title</th>
      <th align="left">Artist</th>
     </tr>
     <xsl:for-each select="catalog/cd">
     <tr>
      <td><xsl:value-of select="title"/></td>
      <td><xsl:value-of select="artist"/></td>
     </tr>
     </xsl:for-each>
   </table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

ในการใช้ XSL style sheet สำหรับแปลงเอกสาร XML ให้อยู่ในรูปแบบที่กำหนด จากตัวอย่าง tag ที่ขึ้นต้นด้วย xsl จะเป็น tag ที่ใช้ namespace ในการอ้างอิงรูปแบบ ซึ่งประกาศไว้ที่ http://www.w3.org/1999/XSL/Transform
ผู้เขียน goragod โพสต์เมื่อ 03 เม.ย. 2551 เปิดดู 17,872 ป้ายกำกับ XML คืออะไร
^