Introduction
All the modern browsers contain built-in XML parsers which are used to convert a string into an XML DOM object and vice versa. The XML DOM object contains properties and methods which are used to manipulate the XML.
Parsing a String to XML
var text = "<author>" +
"<FirstName>Bob</FirstName>" +
"<LastName>Ross</LastName>" +
"</author>";
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(text, "text/xml");
console.log(xmlDoc);
From the above code, you can observe that the DomParser() object is created which is used to convert the string into XML using the -method parseFromString.
The above image shows the XML which is converted from string.
var text = "<author>" +
"<FirstName>Bob</FirstName>" +
"<LastName>Ross</LastName>" +
"</author>";
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(text, "text/xml");
console.log(xmlDoc);
console.log(xmlDoc.all)
var text = "<author>" +
"<FirstName>Bob</FirstName>" +
"<LastName>Ross</LastName>" +
"</author>";
All the properties are used to get a list of nodes in XML.
var text = "<author>" +
"<FirstName>Bob</FirstName>" +
"<LastName>Ross</LastName>" +
"</author>";
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(text, "text/xml");
console.log(xmlDoc);
console.log(xmlDoc.all)
console.log(xmlDoc.getElementsByTagName("FirstName")[0].textContent);
The getElementsByTagName method is used to get the information about the node based on the Tag Name.
Parsing XML to String
<script>
var text = "<author>" +
"<FirstName>Bob</FirstName>" +
"<LastName>Ross</LastName>" +
"</author>";
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(text, "text/xml"); //string to XML
console.log(xmlDoc);
console.log(xmlDoc.all)
console.log(xmlDoc.getElementsByTagName("FirstName")[0].textContent);
var xmlString = (new XMLSerializer()).serializeToString(xmlDoc); // XML to String
console.log(xmlString);
</script>
Conclusion
We saw how to parse a string to XML and XML to string using the JavaScript. I hope you have enjoyed this post.
Thank you for reading!
#javascript #xml #xmldom #developer