Mikh Bor
Mikh Bor

Reputation: 1

Xpath to select node value based on another node value

I'm quite a novice with Xpath.

Suppose I have an xml catalog to import goods into an e-shop:

<categories>
    <category id="26">Jackets</category>
    <category id="27">Jeans</category>
    <category id="28">Sweaters</category>
    <category id="29">Shirts</category>
    ...
</categories>

<goods>
    <good id="123">
        <categoryId>26</categoryId>
        <label>D&G</label>
        <color>Black</color>
        <size>M, XL</size>
    </good>
    ...
<goods>

The first part of the catalog is a list of goods' categories, the second part is a list of the goods. Each good has a <categoryId> which value equals the "id" attribute of some <category> from the <categories> list.

From the code above I need to get a good's description like this: Category: Jackets; Label: D&G; Color: Black; Size: M, XL.

Label, Color and Size can be picked directly from the <good> context, and it's not the problem. But for the Category I have only an id which is 26 and which matches the id of the Jackets category from the <categories> context.

So my goal is to select the value of the <category id="26">Jackets</category> node using the value of the <categoryId>26</categoryId> node.

Thank you much.

Upvotes: 0

Views: 2744

Answers (2)

kjhughes
kjhughes

Reputation: 111491

To selected the category associated with a good that has an @id of 123, use this XPath:

//categories/category[@id = //goods/good[@id='123']/categoryId]

Upvotes: 1

JLRishe
JLRishe

Reputation: 101652

Assuming you have retrieved the value 26 from the categoryId element already, the XPath to select the element with "Jackets" in it would be along the lines of:

//categories/category[@id = "26"]

Depending on what language you're using, you may need to incorporate that 26 using string concatenation, or in XSLT, you can use a variable in the expression directly:

//categories/category[@id = $categoryId]

(However, in XSLT, a better approach would be to use keys).

Upvotes: 0

Related Questions