Search code examples
xmlxpathstring-length

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.


Solution

  • 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]