views:

636

answers:

3

Hi, 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.

A: 

/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.

Paul Butcher
+1  A: 

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

Robert Christie
A: 

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.

Anthony