XML Parser - Script Include
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
08-06-2024 10:05 AM
I'm trying to create a catalog item where a REST API function is called to reach out to a XML URL to return the names of the clusters and populate this info in a selectable select box so that the user can select one of the names from the drop down.
My API Response message comes back with the correct data so I know that's working, but I think there's an issue with my script include:
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
08-06-2024 11:12 PM
It looks like you’re on the right track with your script include, but there are a few adjustments needed to ensure it works correctly with your XML data. I assume your XML structure looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<topology>
<cluster name="ClusterA"/>
<cluster name="ClusterB"/>
<cluster name="ClusterPlaceholder"/>
<cluster name="ClusterC"/>
</topology>
Based on this structure, here’s a refined version of your script that should address the issues:
var WebSphereTopologyParser = Class.create();
WebSphereTopologyParser.prototype = {
initialize: function() {},
getClusterNames: function() {
var restMessage = new sn_ws.RESTMessageV2('WebSphereTopologyXML', 'GetTopologyXML');
var response = restMessage.execute();
var responseBody = response.getBody();
var parser = new XMLDocument2();
parser.parseXML(responseBody);
var clusterNames = [];
// Use a fixed range to avoid infinite loop
for (var index = 1; index <= 10; index++) {
var cluster = parser.getNode('/topology/cluster[' + index + ']');
if (!cluster) break; // Exit loop if no more clusters
var clusterName = cluster.getAttribute('name');
if (clusterName && !clusterName.includes('Placeholder')) {
clusterNames.push(clusterName);
}
}
return JSON.stringify(clusterNames);
},
type: 'WebSphereTopologyParser'
};
Key Changes:
Fixed Iteration Range: Instead of using .length which can be problematic if the number of nodes is unknown, I’ve used a fixed range of 10 iterations. This avoids potential infinite loops and ensures that your script will not break if the number of clusters exceeds expectations.
Node Retrieval: The parser.getNode('/topology/cluster[' + index + ']') approach allows us to retrieve nodes individually and check if they exist before processing them. This avoids issues if the XML structure changes or if there are fewer nodes than expected.
Error Handling: The if (!cluster) break; condition ensures that we exit the loop once we no longer find clusters, making the script more robust.
These changes should help your script correctly parse the XML and extract the cluster names. Let me know if you need further assistance!