Sử dụng phương thức attr() của jQuery để trích xuất giá trị attribute từ chuỗi XML.
Ví dụ
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Parse XML attribute</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<script>
var xmlString = '<Game id="101" details="Play the game and win the amount">'
+ '<gameName name="Cricket" content="/localhost/content/game/play/" />'
+ '<gameName name="Tennis" content="/localhost/game/all/scratch/" />'
+ '</Game>';
console.log("Game Details: " + $(xmlString).attr("details"));
</script>
</body>
</html>
Cách chạy
Lưu index.html, mở Live Server, xem console.
Kết quả
Game Details: Play the game and win the amount
Lưu ý: jQuery parse chuỗi XML thành đối tượng jQuery, sau đó .attr("tên") lấy giá trị attribute.