XPath concat multiple nodes

僤鯓⒐⒋嵵緔 提交于 2019-12-06 06:12:46

问题


I'm not very familiar with xpath. But I was working with xpath expressions and setting them in a database. Actually it's just the BAM tool for biztalk.

Anyway, I have an xml which could look like:

<File>
  <Element1>element1<Element1>
  <Element2>element2<Element2>
  <Element3>
    <SubElement>sub1</SubElement>
    <SubElement>sub2</SubElement>
    <SubElement>sub3</SubElement>
  <Element3>
</File>

I was wondering if there is a way to use an xpath expression of getting all the SubElements concatted? At the moment, I am using:

 /*[local-name()='File']/*[local-name()='Element3']/*[local-name()='SubElement']

This works if it only has one index. But apparently my xml sometimes has more nodes, so it gives NULL. I could just use

/*[local-name()='File']/*[local-name()='Element3']/*[local-name()='SubElement'][0]

but I need all the nodes. Is there a way to do this?

Thanks a lot!

Edit: I changed the XML, I was wrong, it's different, it should look like this:

<item>
    <element1>el1</element1>
    <element2>el2</element2>
    <element3>el3</element3>
    <element4>
        <subEl1>subel1a</subEl1>
        <subEl2>subel2a</subEl2>
    </element4>
    <element4>
        <subEl1>subel1b</subEl1>
        <subEl2>subel2b</subEl2>
    </element4>
</item>

And I need to have a one line code to get a result like: "subel2a subel2b";

I need the one line because I set this xpath expression as an xml attribute (not my choice, it's specified). I tried string-join but it's not really working.


回答1:


string-join(/file/Element3/SubElement, ',')




回答2:


/File/Element3/SubElement will match all of the SubElement elements in your sample XML. What are you using to evaluate it?

If your evaluation method is subject to the "first node rule", then it will only match the first one. If you are using a method that returns a nodeset, then it will return all of them.




回答3:


You can get all SubElements by using:

//SubElement

But this won't keep them grouped together how you want. You will want to do a query for all elements that contain a SubElement (basically do a search for the parent of any SubElements).

//parent::SubElement

Once you have that, you could (depending on your programming language) loop through the parents and concatenate the SubElements.



来源:https://stackoverflow.com/questions/1974253/xpath-concat-multiple-nodes

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