Home > Software design >  Parse XML into INT to sum numbers up
Parse XML into INT to sum numbers up

Time:01-06

I have an XML that I'm trying to get a sum out of. The number is either 0 or 1, and I want to get a sum of all the numbers. The XML looks like this:

<alerts>
    <alert1>0</alert1>
    <alert2>1</alert2>
    <alert3>1</alert3>
    <alert4>0</alert4>
</alerts>

My current code (wrong) looks like this:

xpath = require('xpath');
xmldom = require('xmldom');

doc = new xmldom.DOMParser().parseFromString("sourceXml");

var count = xpath.select("alerts/alert1", doc).toString();
count  = xpath.select("alerts/alert2", doc).toString();
count  = xpath.select("alerts/alert3", doc).toString();
count  = xpath.select("alerts/alert4", doc).toString();


var result = count;

Obviously since they're strings it results in "0110" as a string and not "2" as an INT. I tried wrapping each in parseInt but that just returns NaN. Any help would be appreciated.

Edit:

parseInt(xpath.select("alerts/alert3", doc).toString());

parseInt(xpath.select("alerts/alert3", doc)); 

Tried both but I'm not very experienced with JavaScript so it could be a syntax issue.

CodePudding user response:

From the xpath.select() documentation...

The return value is determined based on the result type of the expression (which can always be predicted ahead of time based on the expression's syntax):

  • A boolean value if the expression evaluates to a boolean value.
  • A number if the expression evaluates to a numeric value.
  • A string if the expression evaluates to a string.
  • If the expression evaluates to a nodeset:
    • An array of 0 or more nodes if single is unspecified or falsy
    • A single node (the first node in document order) or undefined if single is truthy

All your results are arrays, each containing a single node.

You can actually coerce the values to be numeric automatically by using the XPath number function

const count = xpath.select("number(alerts/alert1)", doc)
   xpath.select("number(alerts/alert2)", doc)
   xpath.select("number(alerts/alert3)", doc)
   xpath.select("number(alerts/alert4)", doc)

Perhaps an easier option would be to simply use the XPath sum function

const count = xpath.select(
  "sum(alerts/*[self::alert1 or self::alert2 or self::alert3 or self::alert4])",
  doc
)

See also XPath to select multiple tags

  •  Tags:  
  • Related