How to use XPath In Javascript
XPath is a query language that is used for choosing nodes from XML documents. Define an XML string to represent a bookstore with a book element having a category attribute. Locate the category of the book element after parsing this XML string using XPath. Then evaluate the expression with the evaluate method which selects the category attribute of a book. It then retrieves the result using stringValue and logs its value to the console that is “magic”.
Syntax:
let attributeValue = xmlDoc.evaluate("/path/to/tag/@attribute", xmlDoc, null, XPathResult.STRING_TYPE, null).stringValue;
Example: The example below shows how to get attribute value from XML with Java Script using XPath.
<!DOCTYPE html>
<html>
<head>
<title>Using XPath</title>
</head>
<body>
<h2>Using XPath</h2>
<script>
let xmlString =
"<bookstore><book category='magic'>Harry Potter</book></bookstore>";
let xmlDoc = new DOMParser()
.parseFromString(xmlString, "text/xml");
let category = xmlDoc.evaluate("/bookstore/book/@category",
xmlDoc, null,
XPathResult.STRING_TYPE,
null).stringValue;
console.log(category);
</script>
</body>
</html>
Output:
How to get Attribute Value from XML using JavaScript?
To get the attribute values from XML in JavaScript, We can use DOM manipulation or XPath querying and even use regular expressions to efficiently retrieve attribute values from XML documents.
Below are the approaches to get attribute value from XML with Java Script:
Table of Content
- Using DOM Parser
- Using XPath
- Using Regular Expressions
- Using the attr() method in jQuery