Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum String-Length of two different nodes with Xpath - Sum two nodes string-length

The following xpath does not seem to work:

//FullName[sum(string-length(FirstName) | string-length(LastName))>= 30]

Error: Expression must evaluate to a node-set.

XML snippet

<FullName>
 <FirstName>somereallylongfirstnameguy</FirstName>
 <LastName>somereallylonglasttnameguyabcdefghijklmnopqrstuv</LastName>
</FullName>

I know the sum function adds number together, and string length returns numbers.

The following expression works fine:

//FullName[string-length(FirstName) >= 1]

Any help would be appreciated.

like image 391
james31rock Avatar asked Oct 19 '11 21:10

james31rock


2 Answers

The sum() function expects a node-set, which you try to provide with your string-length() calls, but that fails. sum() does not appear to be the appropriate function here.

You can either just add up the lengths directly in the predicate:

//FullName[string-length(FirstName)+string-length(LastName) >= 30] 

Or you can use concatenate first, then get the length:

//FullName[string-length(concat(FirstName,LastName)) >= 30] 

Or, if your snippet is representative for all FullName elements, just consider the length of all text node contents of the context node like this:

//FullName[string-length() >= 30] 
like image 154
mousio Avatar answered Nov 11 '22 13:11

mousio


If the number of names can vary (such as Middle Initil, orefix, suffix, etc...), it is generally not possible to get the wanted sum with a single XPath 1.0 expression.

In XPath 2.0 this is possible:

//FullName[sum(*/stringlength()) ge 30]
like image 2
Dimitre Novatchev Avatar answered Nov 11 '22 13:11

Dimitre Novatchev