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 thegenre
attribute set tofiction
Output of above example:
<book genre="fiction">
<title>The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
</book>