0

i have XML file like this

<?xml version="1.0" encoding="ISO-8859-1"?>
<childrens>
  <child id="1" value="Root Catalog" parent_id="0">
    <child id="2" value="Apparel" parent_id="1">
      <child id="4" value="Shirts" parent_id="2"/>
      <child id="5" value="Pants" parent_id="2"/>
    </child>
    <child id="3" value="Accessories" parent_id="1">
      <child id="6" value="Handbags" parent_id="3"/>
      <child id="7" value="Jewelry" parent_id="3"/>
    </child>
     .
     .
     .
    <child id='bla bla'>
       <child id='bla bla'>
           <child id="1005" value="test1" parent_is="1111"/>
           <child id="1006" value="test12" parent_is="1111"/>
           <child id="1007" value="test123" parent_is="1111"/>
        <child>
    </child>
  <child >
</childrens>

i have written this jQuery code to get the leaf element(which has no child) for example here leaf node is which have id 4,5,6,7,1005,1006 and 1007

$.ajax({
    type: "GET",
    url: "test.xml",
    dataType: "xml",
    success: function(xml) {
        $(xml).find('child').children().each(function(){
            var id = $(this).attr('entity_id');
            alert(id)
        });
    }
});

it is not working

1
  • Can you clarify what "not working" means? Is it not producing any alerts, not the expected number, not the correct value... Jan 26, 2013 at 14:57

1 Answer 1

1

If you want to select only the child elements that are "leaf nodes" and do not have any children, you can use the :empty selector and change your selection to:

find('child:empty')

and then iterate over the selected elements, rather than it's children by removing .children()

Your example XML does not have any attributes called entity_id. For the example XML you would select attr('id').

$.ajax({
    type: "GET",
    url: "test.xml",
    dataType: "xml",
    success: function(xml) {
        $(xml).find('child:empty').each(function(){
            var id = $(this).attr('id');
            alert(id)
        });
    }
});

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.