1

There have been a lot of other posts related to this but I can't seem to find the answer to my question. I'm trying to parse an XML file of the following form to return only the items under the 'subGroup' node.

Here is the sample XML:

<?xml version="1.0" ?>
<resultsGroup>
  <item>
      <id></id>
      <title></title>
      <description></description>
  </item>
  <item>
      <id></id>
      <title></title>
      <description></description>
  </item>
  <subGroup>
      <item>
          <id></id>
          <title></title>
          <description></description>
      </item>  
      <item>
          <id></id>
          <title></title>
          <description></description>
      </item>  
      <item>
          <id></id>
          <title></title>
          <description></description>
      </item>  
  </subGroup>
</resultsGroup>

And here is currently what I'm using to parse it:

$.get(url,{},function(data){
    $('item',data).each(function(i){
        var id = $(this).find("id").text();
        var title = $(this).find("title").text();
        var description = $(this).find("description").text();

        list.append('<li>' + id + ':' + title + ':' + description + '</li>');
    });
});

The problem is that the items listed under the 'resultsGroup' are also being selected by $('item',data).each(). I'd appreciate it if someone could explain how to select just those elements under a specific node, in this case the 'subGroup' node.

Thanks in advance for your help!

1 Answer 1

2

Use $('subGroup>item',data)

Sign up to request clarification or add additional context in comments.

5 Comments

Wow, that was fast! Thanks Doug. Is there somewhere online that explains JQuery XML selectors in more detail? I couldn't find anything and I'd love to better understand them. Thanks again!
jQuery no longer supports XPath, but its CSS selectors work with XML. See docs.jquery.com/Selectors
Nice Doug- this was a hard one to find
@DougDomeny, Is there any way to read data based on the attributes. For instance, <subGroup> <item id = "1"> <title></title> <description type="string" label="Details"></description> </item></subGroup>
@Ahamed, yes, there are many jQuery operators for use with attributes. For example, $('subGroup>item[id="1"]',data) to select elements that have the specified attribute with a value exactly equal to a certain value. See jQuery Selector Reference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.