XPath to return a array of string concatenation of multiples child node values

旧城冷巷雨未停 提交于 2019-12-24 10:44:43

问题


If I have the below XML

<div>
    <p>1</p>
</div>
<div>
    <p>2</p> 3 
</div>
<div>
    <p>4</p> 5 <p>6</p>
</div>

How to specify a xpath to return a array of strings like this:

{ 1, 2, 46 }

All attempts I did returned the following result:

{ 1, 2, 4, 6}    

回答1:


Here you are

concat(string-join(//div[count(p) = 1]/p, ',') , ',' , string-join(//div[count(p) &gt; 1]/string-join(p, ''), ','))

will return 1,2,46

As you will need to concatenate some p tags under the same div tag so in all the cases this will result string which can be converted to array by tokenise() function.

Here's the trick:

First part

string-join(//div[count(p) = 1]/p, ',')

This will only select the div which have only one p tag .. so no concatenation required here. this will get

1,2

Second Part string-join(//div[count(p) > 1]/string-join(p, ''), ',')

This part concat all the p tags under the same div, then join all of the dev that has more than one p chid tag.

this part will get

46

Example:

<div>
    <p>1</p>
</div>
<div>
    <p>2</p> 3 
</div>
<div>
    <p>4</p> 5 <p>6</p>
</div>
<div>1<p>2</p>3 , 1<p>2</p><p>3</p>4</div>

The output will be

1,2,46,223

If you want it as array you can tokenize it.

tokenize(concat(string-join(//div[count(p) = 1]/p, ',') , ',' , string-join(//div[count(p) &gt; 1]/string-join(p, ''), ',')) , ',')

I hope this could help.

Please correct me if I'm wrong.



来源:https://stackoverflow.com/questions/29650555/xpath-to-return-a-array-of-string-concatenation-of-multiples-child-node-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!