开发者

issue with a seemingly simple XML parse

I have an XML file:

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

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]

That's all good. Now, I would assume that:

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

would return just the first two items, the two under the first item开发者_如何学JAVA_container. However, it returns all four items which I don't understand.

How can I just access the first two items?


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜