Below is JavaScript method that reads and filters XML nodes based on specific criteria from a given XML string. This method uses the DOMParser to parse the XML string and XPath to filter the desired nodes.

/**
 * Filters XML nodes from a given XML string based on a specific condition.
 * @param {string} xmlString - The XML string to be parsed.
 * @param {string} xpathExpression - The XPath expression to filter nodes.
 * @returns {Array} - An array of filtered nodes.
 */
function filterXMLNodes(xmlString, xpathExpression) {
    // Check if the input is valid
    if (!xmlString || typeof xmlString !== "string") {
        throw new Error("Invalid XML string provided.");
    }

    if (!xpathExpression || typeof xpathExpression !== "string") {
        throw new Error("Invalid XPath expression provided.");
    }

    try {
        // Parse the XML string
        const parser = new DOMParser();
        const xmlDoc = parser.parseFromString(xmlString, "application/xml");

        // Check for parsing errors
        const parseError = xmlDoc.getElementsByTagName("parsererror");
        if (parseError.length > 0) {
            throw new Error("Error parsing XML string.");
        }

        // Use XPath to filter nodes
        const xpathResult = xmlDoc.evaluate(
            xpathExpression,
            xmlDoc,
            null,
            XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
            null
        );

        // Collect filtered nodes
        const nodes = [];
        for (let i = 0; i < xpathResult.snapshotLength; i++) {
            nodes.push(xpathResult.snapshotItem(i));
        }

        return nodes;
    } catch (error) {
        console.error("Error processing XML:", error);
        return [];
    }
}

// Example usage
const xmlData = `
<books>
    <book genre="fiction">
        <title>The Great Gatsby</title>
        <author>F. Scott Fitzgerald</author>
    </book>
    <book genre="non-fiction">
        <title>Sapiens</title>
        <author>Yuval Noah Harari</author>
    </book>
</books>
`;

const xpathExpression = "//book[@genre='fiction']";
const filteredNodes = filterXMLNodes(xmlData, xpathExpression);

filteredNodes.forEach((node) => {
    console.log(node.outerHTML); // Log the filtered nodes as XML strings
});

In above example you can customize the xpathExpression to filter nodes based on different criteria.

  • XML Parsing: The DOMParser converts the XML string into a document object (xmlDoc).XPath Evaluation:
  • The evaluate method of the document object applies the given XPath expression to filter nodes.
  • Node Collection: The method iterates over the XPathResult and collects matching nodes into an array.
  • Example: The example filters all <book> nodes with the genre attribute set to fiction

Output of above example:

<book genre="fiction">
    <title>The Great Gatsby</title>
    <author>F. Scott Fitzgerald</author>
</book>

Leave a Reply

Your email address will not be published. Required fields are marked *

Explore More

addchild and removeChild DOM methods for Edge and Chrome

Below we are creating a JavaScript utility that fully supports the functionality of the DOM (like appendChild, removeChild, etc.) in Microsoft Edge and other modern browsers involves wrapping standard DOM

How to remove JavaScript Objects from memory

To remove unused objects and improve memory management in JavaScript, you generally rely on the JavaScript engine’s garbage collection mechanism. However, you can aid this process by explicitly removing references

JavaScript method to remove child node

Create a JavaScript method that will take 2 parameters, first parameter will take complete XML as string and second will take XML node object which need to be removed from