开发者

Traverse through xml using duplicate data using jquery

I am a newbie and was trying to traverse a ajax loaded xml file. I am trying to populate all the names and city from it, and if the name is common then i would just append the city for the common name.

my xml file

       <Info>
       <detail>
       <country>US</country>
       <name>Edward</state>
       <city>San bruno</city> 
       </detail>

       <detail>
       <country>US</country>
       <name>Edward</state>
       <city>Charleston </city> 
       </detail>
       </info>

I an trying to show it in a format like this

       Edward
       San Bruno
       Charleston

My jquery code looks like this

       $.ajax({
       type: "GET",
   url: "sheet.xml",
   dataType: "xml",
   success: function(xml) {
        $(xml).find('detail').each(function(){
            var Pname = $(this).find('name').text();
            $('<div class="items" id="link">         开发者_StackOverflow中文版       </div>').html('<Strong>'+name+'</Strong>').appendTo('#content');
            if(Pname = $(xml).find('name').each(function(){
            var city = $(this).find('city').text();
            var full = name + ","+city;
            $('<div class="items" id="link"></div>').html('<a href="'+city+'">'+city+'</a>').appendTo('#content');
            });

I am just not able to loop it again so that I can find the guy with same name but a different city hence placing them together according to different location. any Help would be appreciated. Thanks in advance..


You should be able to modify this to work in your success function:

var xmlString = "<Info><detail><country>US</country><name>Edward</name><city>San bruno</city> </detail><detail><country>US</country><name>Edward</name><city>Charleston </city> </detail><detail><country>US</country><name>John</name><city>Charleston </city> </detail><detail><country>US</country><name>John</name><city>Dallas</city></detail></Info>",
xmlDoc = $.parseXML(xmlString),
$xml = $(xmlDoc),
$name = $xml.find("name");

var prevName = "";

$name.each(function() {
    var currNode = $(this);
    var currName = currNode.text(); 

    if (currName != prevName) {
        document.write(currName + "<br />");
        document.write(currNode.next().text() + "<br />");
        prevName = currName;
    } else {
        document.write(currNode.next().text() + "<br />");
    }
});

jsfiddle: http://jsfiddle.net/jensbits/Z6Bst/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜