Search code examples
javascriptjqueryxmlrecursive-datastructuresparsexml

jquery parse xml with unlimited child level category


I'm fairly new on parsing xml with jquery, so if my question looks like noobish, please forgive me.

I have an xml it contains my recursive categories. Some of them has sub categories, some of them not. It has some deep level categories under sub categories.

Sample of xml;

<Urunler>
    <Urun>
        <ID>1</ID>
        <Parent>0</Parent>
        <Name>Red</Name>
    </Urun>
    <Urun>
        <ID>2</ID>
        <Parent>0</Parent>
        <Name>Green</Name>
    </Urun>
    <Urun>
        <ID>3</ID>
        <Parent>0</Parent>
        <Name>Blue</Name>
    </Urun>
    <Urun>
        <ID>4</ID>
        <Parent>3</Parent>
        <Name>Sky</Name>
    </Urun>
    <Urun>
        <ID>5</ID>
        <Parent>3</Parent>
        <Name>Sea</Name>
    </Urun>
    <Urun>
        <ID>6</ID>
        <Parent>5</Parent>
        <Name>Fish</Name>
    </Urun>
    <Urun>
        <ID>7</ID>
        <Parent>4</Parent>
        <Name>Bird</Name>
    </Urun>
</Urunler>

Desired HTML output

<ul>
    <li>Red</li>
    <li>Green</li>
    <li>Blue
        <ul>
            <li>Sky
                <ul>
                    <li>Bird</li>
                </ul>
            </li>
            <li>Sea
                <ul>
                    <li>Fish</li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

I find an example on https://codereview.stackexchange.com/questions/43449/parsing-xml-data-to-be-put-onto-a-site-with-jquery unfortunately it supports only first child level.

if needed; i call my xml via $.ajax

$.ajax({
   url: 'webservice/Resim/Kategori.xml',
   dataType: 'xml',
   cache:true,
   success: parseXml
});

Any help will greatly appricated.


Solution

  • You have to iterate over the Urun elements, and append to the right place in the new UL element

    function parseXml(xml) {
    
        var ul = $('<ul />');
    
        $(xml).find('Urun').each(function(index, item) {
            var parent = parseInt( $(this).find('Parent').text() , 10 );
            var li     = $('<li />', {
                text : $(this).find('Name').text(),
                id   : $(this).find('ID').text()
            });
    
            if (parent !== 0) {
                var parentEl = ul.find('li#' + parent);
    
                if ( parentEl.find('ul').length === 0 ) 
                    parentEl.append( $('<ul />') );
    
                parentEl.find('ul').append(li);
    
            } else {
                ul.append(li);
            }
    
        });
    
        $('body').append(ul);
    
    }
    

    FIDDLE