แท็ก <x:set> ใช้ตั้งค่าตัวแปรให้เท่ากับค่าผลลัพธ์ของ XPath Expression
ประเภทข้อมูลที่ได้: boolean → java.lang.Boolean, string → java.lang.String, number → java.lang.Number
แอตทริบิวต์ของ <x:set>
| แอตทริบิวต์ | คำอธิบาย | จำเป็น | ค่าเริ่มต้น |
|---|---|---|---|
| var | ชื่อตัวแปรที่จะเก็บค่าผลลัพธ์ | ใช่ | Body |
| select | XPath Expression ที่ต้องการประเมินค่า | ไม่ | None |
| scope | ขอบเขตของตัวแปร | ไม่ | Page |
ตัวอย่างการใช้งาน
<%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="x" uri="https://java.sun.com/jsp/jstl/xml" %>
<html>
<head>
<title>JSTL x:set Tag</title>
</head>
<body>
<h3>Books Info:</h3>
<c:set var="xmltext">
<books>
<book>
<name>Padam History</name>
<author>ZARA</author>
<price>100</price>
</book>
<book>
<name>Great Mistry</name>
<author>NUHA</author>
<price>2000</price>
</book>
</books>
</c:set>
<x:parse xml="${xmltext}" var="output"/>
<x:set var="fragment" select="$output//book"/>
<b>ข้อมูลหนังสือทั้งหมด:</b> <c:out value="${fragment}" />
</body>
</html>
ผลลัพธ์
Books Info: ข้อมูลหนังสือทั้งหมด: [[book: null], [book: null]]
หมายเหตุ: ผลลัพธ์เป็น NodeList การเข้าถึงค่าภายในควรใช้ <x:out> หรือ <x:forEach> แทนการ print ตรงๆ