Sara44
Sara44

Reputation: 422

Getting products from a category in XML

I have an XML file that I am using Ajax to read:

<prod id="6786345">
    <pId>0436</pId>
    <text>
        <name>Blue widget</name>
        <desc>Stunning blue widget</desc>
    </text>
    <cat>
        <myCatId>252</myCatId>
        <myCat>Widgets</myCat>
    </cat>
    <pId>0437</pId>
    <text>
        <name>Red widget</name>
        <desc>Amazing red widget</desc>
    </text>
    <cat>
        <myCatId>252</myCatId>
        <myCat>Widgets</myCat>
    </cat>
    <pId>0438</pId>
    <text>
        <name>Cheeseburger</name>
        <desc>Healthy delight</desc>
    </text>
    <cat>
        <myCatId>253</myCatId>
        <myCat>Burgers</myCat>
    </cat>
</prod>

And my working Ajax that pulls just the name without belonging to a category is this:

$(document).ready(function(){
        $.ajax({
        type: "GET",
        url: "feed.xml",
        dataType: "xml",
        success: function(xml) {

        $(xml).find('text').each(function(){

        var title = $(this).children('name').text();

How do I return the text name for just items in category 252?

Upvotes: 0

Views: 105

Answers (1)

Jim Garrison
Jim Garrison

Reputation: 86774

You have to find myCatId nodes with value 252, then navigate backwards. In XPath, this would be

../preceding-sibling::text/name`

Given the weird XML layout this will of course fail (return the wrong value) if there is no <text> node between the preceding <cat> and <pId> nodes.

EDIT: I don't have much experience with jQuery, but from a quick read of the docs, I think it would look something like this:

var title = $(this).parent().prev("text").children("name").text();

But remember that this depends on a broken XML structure which uses adjacency to relate entities when it should be using hierarchy. If you can fix the XML you will be much better off.

Upvotes: 1

Related Questions