views:

44

answers:

1

Hi all,

I have an xml file as follows:

<products>
    <foundation label="New Construction">

        <series label="Portrait Series" startImg="img/blank.png">
            <item_container nr="1" label="Firebed">
                <item next="11" id="" label="Logs Black Brick">img/PortraitSeries/logs-black-brick.png</item>
                <item next="12" id="" label="Logs Red Brick">img/PortraitSeries/logs-red-brick.png</item>
            </item_container>

            <item_container nr="2" label="Fronts">

            <item next="21" id="569LFP" label="Ledge Front - Patina">img/New_PortraitSeries/patina_front.png</item>
            <item next="22" id="569LFB" label="Ledge Front - Black">img/New_PortraitSeries/black_front.png</item>
            </item_container>
        </series>

    </foundation>

</products>

I'm using Nokogiri to parse. What I want to do is operate on each item element within the scope of each item_container. Meaning, I want to do certain things with each item while knowing which item_container they are under.

Here is some code to get at the first item_container:

foundation = @doc.at_xpath("//foundation")
ic = foundation.children.xpath("//series").children.xpath("//item_container")[0]

All good. Now I would assume that:

ic.children.xpath("//item") 

would return just the first 2 items, the 2 under the first item_container. However, it returns all 4 items which I don't understand.

How can I just access the first 2 items?

Thanks.

A: 

An XPath beginning with 2 slashes selects the nodes with that name regardless of their position in the document. That's why you can select your foundation with //foundation even though starting from the root of the XML it is contained within <products>

Having selected the first item_container, ic as in the question you can select the 2 items under it with ic.xpath('item')

e.g.

irb(main):120:0> items = ic.xpath('item')
=> [#<Nokogiri::XML::Element:0x15b030a name="item" attributes=[#<Nokogiri::XML::
Attr:0x15b0260 name="next" value="11">, #<Nokogiri::XML::Attr:0x15b0256 name="id
...
irb(main):121:0> items.size
=> 2
irb(main):122:0> items[0].attribute('label').value
=> "Logs Black Brick"
irb(main):123:0> items[1].attribute('label').value
=> "Logs Red Brick"
irb(main):124:0>
mikej
wow - should have reviewed xpath syntax, thought the 2 slashes was required, apparently not.thanks mike!
46and2