0

Is it possible to sum the temperatures following XML:

<days>
    <day><temperature>40 F</temperature></day>
    <day><temperature>45 F</temperature></day>
    <day><temperature>50 F</temperature></day>
</days>

In xpath 2.0, I could get the average of the three numbers using

avg(//days/day/temperature/number(translate(.,' F','')))

Is it possible to write an expression in pure xpath 1.0 that can do the same thing? This response to a question regarding the use of 'sum' on impure nodes in xpath 1.0 causes me to think that maybe it's not.

So, to summarize, is there any way to get the average temperature from these impure nodes using only an xpath 1.0 expression?

Doug Bradshaw
  • 1,452
  • 1
  • 16
  • 20
  • I'm sure this can't be done using pure XPath 1.0, and even more confident knowing that [@Michael Kay](http://stackoverflow.com/users/415448/michael-kay) thought the same – har07 Mar 29 '16 at 13:29

1 Answers1

1
sum(//days/day/temperature/number(translate(.,' F',''))) div count(//days/day/temperature)
Kim Homann
  • 3,042
  • 1
  • 17
  • 20
  • Of course it is. `avg()` is not available in XPath 1.0 but `number()` is. Tried it with Altova XMLSpy Enterprise 2016 rel. 2. – Kim Homann Mar 29 '16 at 12:16
  • It isn't about availability of the function, it is the syntax that is not allowed. For example : `temperature[number()]` is fine, but `temperature/number()` triggers exception in xpath 1.0 – har07 Mar 29 '16 at 12:19
  • Sorry, but with the above XPath 1.0 expression, I don't get any exception. I explicitly set my XPath query mode to "1.0". My output is: `xs:double 45` – Kim Homann Mar 29 '16 at 12:22
  • Hmm. This expression raises an "Invalid expression" exception on my particular destination parser (python lxml etree xpath). It's interesting that the Altova parser seems to be more forgiving. – Doug Bradshaw Mar 29 '16 at 12:37
  • @KimHomann Maybe your tools still, partially at least, using XPath 2.0 engine somehow, since the tools supports it. Try using something that only implements XPath 1.0, like `lxml` that OP uses, .NET's XML API, etc. The XPath also throw exception when tested in this xpath tester : http://www.xpathtester.com/xpath – har07 Mar 29 '16 at 12:59