将 XML 解析为 INT 以对数字求和

Parse XML into INT to sum numbers up

我有一个 XML,我想从中算出一个总和。数字不是 0 就是 1,我想得到所有数字的总和。 XML 看起来像这样:

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

我当前的代码(错误)是这样的:

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;

显然,因为它们是字符串,所以结果是“0110”作为字符串而不是“2”作为 INT。我尝试将每个包装在 parseInt 中,但只是 returns NaN。任何帮助将不胜感激。

编辑:

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

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

两者都试过了,但我对 JavaScript 不是很有经验,所以这可能是语法问题。

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

您的所有结果都是数组,每个数组包含一个节点。

您实际上可以使用 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)

也许更简单的选择是简单地使用 XPath sum function

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

另见 XPath to select multiple tags

这有什么问题:

const count = xpath.select("sum(alerts/*)", doc)