Open In App

How to Validate XML in JavaScript ?

Last Updated : 17 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Validation of XML is important for ensuring data integrity and adherence to XML standards in JavaScript. There are various approaches available in JavaScript using which validation of the XML can be done which are described as follows:

Using DOM Parser

In this approach, we are using the DOMParser from the “xmldom” package in JavaScript to parse the provided XML string. The code checks for any parsing errors by looking for the presence of a <parsererror> element in the parsed XML document, indicating whether the XML is valid or not.

Run the below command to install xmldom package:

npm install xmldom

Example: This example uses the DOM Parser to validate the XML in JavaScript.

JavaScript
const {
    DOMParser
} = require("xmldom");
const xmlString = `
  <geeks>
      <article>
          <title>Introduction to JavaScript</title>
          <author>GFG</author>
          <published>2024-01-01</published>
      </article>
  </geeks>
  `;
const parser = new DOMParser();
try {
    const xmlDoc = parser
        .parseFromString(xmlString, "text/xml");
    if (xmlDoc
        .getElementsByTagName("parsererror")
        .length > 0) {
        console.error(
            "XML parsing error:",
            xmlDoc
                .getElementsByTagName("parsererror")[0]
        );
    } else {
        console.log("XML is valid.");
    }
}
catch (e) {
    console.error("Error while parsing XML:", e);
}

Output:

XML is valid.

Using Regex

In this approach, we are using a manual tag matching method to validate XML using regex. The function validateFn uses a stack to keep track of opening and closing tags, ensuring they are properly nested. If all tags are matched correctly and the stack is empty at the end, the XML is considered valid; otherwise, it’s flagged as invalid.

Example: To demonstrate using the Tag Matching to validate XML in JavaScript.

JavaScript
const xmlString = `
<geeks>
    <article>
        <title>Introduction to JavaScript</title>
        <author>GFG</author>
        <published>2024-01-01</published>
    </article>
</geeks>
`;

function validateFn(xmlString) {
    let stack = [];
    const regex = /<([^>]+)>/g;
    let match;
    while ((match = regex
        .exec(xmlString)) !== null) {
        if (match[1]
            .charAt(0) === '/') {
            if (stack.length === 0
                ||
                stack.pop() !== match[1].slice(1)) {
                return false;
            }
        } else {
            stack.push(match[1]);
        }
    }
    return stack.length === 0;
}
if (validateFn(xmlString)) {
    console.log("XML is valid.");
} else {
    console.log("XML is not valid.");
}

Output
XML is valid.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads