Pergunta

I have following xml:

<root>
    <table>
        <a>a1</a>
        <b>b1</b>
    </table>
    <table>
        <a>a2</a>
        <b>b2</b>
    </table>
    <table>
        <a>a3</a>
        <b>b3</b>
    </table>
    <table>
        .....
</root>

and I need to join "a" and "b" fields (result: arr[0]="a1b1", arr[1]="a2b2", arr[2]="a3b3" ... arr[N]="aNbN"

With XPath 1.0 I can do such thing only on first item

"concat(/root/table/a, /root/table/b)"

I will always get STRING result: "a1b1", not NODESET.

I've tried with XPath 2.0 (I use net.sf.saxon, Saxon-HE: 9.5.1-4) with foreach, but with not success:

"for $item in /root/table/a return concat($item, 'a')" 

result is XPathConstants.STRING of first item: "a1a"

but when I tried following variant, it's work good

"for $item in /root/table/a return $item" 

result is XPathConstants.NODESET of all items: "a1","a2","a3"

So, how can I get list of "a1b1", "a2b2", "a3b3"...?

Thanks.

Foi útil?

Solução

You can simply use /root/table/concat(a, b), that will give you a sequence of strings. But you will need to use an API that can handle that return type, I think the JAXP API is restricted to XPath 1.0 types so make sure you use Saxon's http://www.saxonica.com/documentation/index.html#!xpath-api/s9api-xpath if you want to take full advantage of XPath 2.0.

Outras dicas

Please try this code:

for $item  in /root/table return concat($item/a, $item/b) 

If the simple concat is not enough in your case, you can try string join:

for $item  in /root/table return string-join(concat($item/a, $item/b),"")

Note the Unicode normalization is not automatically applied to the result of fn:concat. Please check this link for more information.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top