- Elements ใน XML สามารถมี Attributes ได้เช่นเดียวกับ HTML
- Attributes เป็นตัวบอกคุณสมบัติของ Elements
Attributes ในภาษา HTML
แอตทริบิวต์มักจะให้ข้อมูลที่ไม่ได้เป็นส่วนหนึ่งของข้อมูล
โค้ด: เลือกทั้งหมด
<img src="test.gif">
<a href="test.asp">
จะเห็นว่าชนิดของไฟล์ไม่มีความเกี่ยวข้องกับข้อมูล แต่ Attributes สามารถเป็นส่วนหนึ่งกับ Elements ได้
โค้ด: เลือกทั้งหมด
<file type="gif">test.gif</file>
ค่าของ Attributes จะต้องอยู่ภายใต้เครื่องหมาย Quoted เสมอ ไม่ว่าจะเป็นเครื่องหมาย Single Quote ('__') หรือ Double Quote ("__") ก็ได้
ยกตัวอย่างเช่น ให้ Student Element มีอายุ 18 ปี
โค้ด: เลือกทั้งหมด
<student age="18">
โค้ด: เลือกทั้งหมด
<student age='18'>
โค้ด: เลือกทั้งหมด
<team name='Red "Ghost" Devil'>
โค้ด: เลือกทั้งหมด
<team name='Red "Ghost" Devil'>
ดูตัวอย่าง code ข้างล่างนี้
โค้ด: เลือกทั้งหมด
<student age="18">
<firstname>Pichai</firstname>
<lastname>Khewsiri</lastname>
</student>
โค้ด: เลือกทั้งหมด
<student>
<age>18</age>
<firstname>Pichai</firstname>
<lastname>Khewsiri</lastname>
</student>
มันไม่มีกฎตายตัวที่จะต้องใช้ Attribute หรือ Element เเต่ถ้าใช้ใน HTML แบบ Attribute จะเหมาะกว่า เเต่ถ้าใน XML ให้หลีกเลี่ยงการใช้ Attribute แล้วมาใช้แบบ Element เเทน
วิธีที่นิยมใช้ ตัวอย่าง code ข้างล่างนี้จะให้ข้อมูลที่เหมือนกัน
ตัวอย่างที่ 1 ใช้ Date Attribute
โค้ด: เลือกทั้งหมด
<remark date="18/11/2013">
<title>Remark 1</title>
<name>Suree Napheepron</name>
<body>To DO</body>
</remark>
โค้ด: เลือกทั้งหมด
<remark>
<date>18/11/2013</date>
<title>Remark 1</title>
<name>Suree Napheepron</name>
<body>To DO</body>
</remark>
โค้ด: เลือกทั้งหมด
<remark>
<date>
<day>18</day>
<month>11</month>
<year>2013</year>
</date>
<title>Remark 1</title>
<name>Suree Napheepron</name>
<body>To DO</body>
</remark>
ปัญหาที่เกิดจากการใช้ Attributes ใน XML
- Attributes ไม่สามารถมีค่าหลายๆค่าได้ (Elements สามารถทำได้)
- Attributes ไม่สามารถสร้างเป็นโครงสร้างต้นไม้ได้ (Elements สามารถทำได้)
- Attributes ไม่มีความยืดหยุ่น (สำหรับการแก้ไขเปลี่ยนแปลงในอนาคต)
Attributes ใน XML สำหรับ Metadata
บางครั้ง ID ก็สามารถอ้างอิงถึง Elements ได้ ดังตัวอย่างข้างล่างนี้
โค้ด: เลือกทั้งหมด
<messages>
<remark id="01">
<title>Remark 1</title>
<name>Suree Napheepron</name>
<body>To DO</body>
</remark>
<remark id="02">
<title>Remark 2</title>
<name>Somchat Taveesin</name>
<body>Don't forget It!!</body>
</remark>
</messages>