
jQuery parseXML() method
The jQuery.parseXML()
method is a utility function in jQuery that allows you to parse an XML string into an XML Document object. It is commonly used when dealing with XML data retrieved from an API or received as a string in an AJAX response.
Here’s the basic syntax of the jQuery.parseXML()
method:
jQuery.parseXML(xmlString)
Parameters:
xmlString
: The XML string that you want to parse into an XML Document.
Return Value:
The jQuery.parseXML()
method returns an XML Document object that represents the parsed XML data. You can then use this XML Document to traverse and manipulate the XML content using the DOM methods like getElementById()
, getElementsByTagName()
, etc.
Example:
<!DOCTYPE html>
<html>
<head>
<title>jQuery parseXML() Method Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="xmlData" style="display: none;">
<books>
<book>
<title>Book 1</title>
<author>Author 1</author>
</book>
<book>
<title>Book 2</title>
<author>Author 2</author>
</book>
</books>
</div>
<script>
$(document).ready(function() {
// Get the XML string from the hidden div
var xmlString = $("#xmlData").text();
// Parse the XML string into an XML Document object
var xmlDoc = jQuery.parseXML(xmlString);
// Now, you can use the XML Document object to work with the XML data
var books = xmlDoc.getElementsByTagName("book");
for (var i = 0; i < books.length; i++) {
var title = books[i].getElementsByTagName("title")[0].textContent;
var author = books[i].getElementsByTagName("author")[0].textContent;
console.log("Book " + (i + 1) + ": " + title + " by " + author);
}
});
</script>
</body>
</html>
In this example, we have an XML structure inside the hidden #xmlData
div. We retrieve the XML string from the div using the .text()
method and then use jQuery.parseXML()
to parse that XML string into an XML Document object.
Once we have the XML Document object (xmlDoc
), we can use standard DOM methods to access and manipulate the XML data. In this case, we retrieve all the <book>
elements and log their titles and authors to the console.
Keep in mind that if you are working with HTML documents, you may not need to use jQuery.parseXML()
as HTML is already parsed by the browser, and you can directly access its content using DOM methods. This method is mainly useful for dealing with raw XML data.