cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
2257
Views
0
Helpful
3
Replies

Get count of elements in XML file?

bgardner
Level 1
Level 1

UCCX 10.6.

If I have an XML file like this:

<?xml version="1.0" encoding="ISO-8859-1" ?> 
<COLORS>
  <COLOR ID='1'>red</color>
  <COLOR ID='2'>green</color>
  <COLOR ID='3'>blue</color>
</COLORS>

How can I get the total number of COLOR elements under COLORS?

To continue the example, let's say I have a Document variable called dColorListFile with value DOC[/path/to/file.xml] and a Create XML Document step: dColorList = Create XML Document (dColorListFile)

I know how to get individual color names from the file using a Get XML Document Data step like this: sColorName = Get XML Document Data (dColorList, "/descendant::COLORS/child::COLOR[attribute::ID=2]").  (sColorName now contains "green")

Regards

3 Replies 3

Aaron Harrison
VIP Alumni
VIP Alumni

Hi

Firstly, your XML is invalid. You have </color> in lowercase. 

To count instances of the 'COLOR' element, you can use "count(/COLORS/COLOR)" which will return a double.

Aaron

Aaron Please remember to rate helpful posts to identify useful responses, and mark 'Answered' if appropriate!

Aaron-

Thank you for your response.

It was a hastily typed example, I hope you will forgive the formatting mistakes. Of course </color> should have been </COLOR>.

Should I be able to use this in a Get XML Document Data step, like this:

iColorCount = Get XML Document Data (dColorList, "count(//COLORS/COLOR)")

When I do this the application errors.

Something I've just found that works, in a Set step I set iColorCount equal to:

{
    try {
        javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
        javax.xml.parsers.DocumentBuilder builder = factory.newDocumentBuilder();
        org.w3c.dom.Document domDoc = builder.parse(dColorList);
        javax.xml.xpath.XPath XPath = javax.xml.xpath.XPathFactory.newInstance().newXPath();
        String XpathEval = "count(//COLORS/COLOR)";
        Integer RETURNVAL = XPath.evaluate(XpathEval,domDoc);
        return RETURNVAL;
    } catch (java.lang.Exception e) {
        e.printStackTrace();
    }
}

This seems fairly complicated.  I was hoping to find something simpler.

Hi

What you have there is just a call to the underlying Java. It might be that the 'get xml' step doesn't like that specific xPath syntax for some reason though it is clearly valid.

Best way is to see what the MIVR log shows when you hit the step. That will clue you in to the root of the issue usually... but what you have there is perfectly fine, if a little scary for less 'development' inclined engineers ;-)

Aaron

Aaron Please remember to rate helpful posts to identify useful responses, and mark 'Answered' if appropriate!