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

How to Center a Popup Window on Screen

JavaScript window.open() method is used to open a popup window. This popup window will be placed in the center of the screen. This example creates the pop-up window without placing it into

How to hide URL in the popup window opened using window.open

If you are using below code to open a popup window in your web page, then address must be appearing in you pop up window and f you want to

window.showModalDialog is deprecated in Edge and Chrome

If you have a website being compatible with Edge/Chrome and in past it was only compatible with IE 11 and if you are using window.showModalDailog in your JavaScript code, then