Parsing a XML file to find the title attribute

1.2k Views Asked by At

I am naive jQuery programmer, so somebody please help me out with this problem. The first example shows what i am doing and its working. But my dilemma is that the list is created by parsing a XML. If so how would i parse the xml, find the 'title' attribute and then load the corresponding url into a Div. Thanks in advance...

jQuery code

 $('.treeLinks').click(function() {
    var sourceURL = $(this).attr('title');
    $('#content').load(sourceURL);
    });

Corresponding HTML Code

<ul>
<li><a href="#" title="contentArea1.html" class="treeLinks">Link 1</a></li>
<li><a href="#" title="contentArea2.html" class="treeLinks">Link 2</a></li>
</ul>

XML code which needs to be parsed for getting the title attribute

<?xml version="1.0" encoding="UTF-8"?>
<root>
<item id="pxml_1">
  <content><name class="treeLinks"><![CDATA[Root node 1]]></name></content>
 <item id="pxml_2">
 <content><name class="treeLinks"><![CDATA[Child node 1a]]></name>
 <item id="pxml_23">
 <content><name><![CDATA[Child node 1a]]></name></content>
 </item>
 </content>
 </item>
 <item id="pxml_3">
 <content><name><![CDATA[Child node 2b]]></name></content>
 </item>
 <item id="pxml_4">
 <content><name><![CDATA[Child node 3c]]></name></content>
 </item>
</item>
</root>
1

There are 1 best solutions below

3
On

Parse your XML the same way you would html (there's really nothing special about it); This works in Firefox (not sure why IE didn't like it). Save as an .html file for an example.

<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script type="text/javascript">
        //Document Ready: Everything inside this function fires after the page is loaded
        $(document).ready(function () {
            var test = '<?xml version="1.0" encoding="UTF-8"?><root><item id="pxml_1"><content><name class="treeLinks"><![CDATA[Root node 1]]></name></content> <item id="pxml_2"> <content><name class="treeLinks"><![CDATA[Child node 1a]]></name> <item id="pxml_23"> <content><name><![CDATA[Child node 1a]]></name></content> </item> </content> </item> <item id="pxml_3"> <content><name><![CDATA[Child node 2b]]></name></content> </item> <item id="pxml_4"> <content><name><![CDATA[Child node 3c]]></name></content> </item></item></root>';

            //Need to wrap you xml with a root node
            test = "<wrapper>" + test + "</wrapper>";

            $(test).find('.treeLinks').each(function(){
                alert($(this).html());
            });
        });
    </script>
</head>
<body>
</body>
</html>

The rest of your question wasn't really clear. I couldn't figure out how your xml is creating the links above. If you can, clarify the relationship between the XML and your links.

Hope this gets your started!