Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load xml file content into div using jquery

Tags:

jquery

xml

load

How to load the xml file content to a div.

Here is my HTML in which I need to load XML content

<div class="editorial" id="news-container">
</div>

XML Data

<contentprogramming>
    <category name = "My t" id = "1">
        <logo>http://123.png</logo>        
        <channel name="res" id= "1" type="ecommerce">            
            <logo>http://11.png</logo>           
            <items>              
                <item id="1">
                    <image>http://11.jpg</image>
                    <title>Memory Card MSMT2G</title>
                    <details>$6.99</details>
                    <linkurl>http://www.test.com/Sony</linkurl>
                </item>
                <item id="2">
                    <image>http://i2.jpg</image>
                    <title>Apple iPad </title>
                    <details>$579.95</details>
                    <linkurl>http://www.test.com/Apple</linkurl>
                </item> 
            </items>
        </channel>
    </category>
</contentprogramming>

And xml file name is something.xml

I tried several ways but it didn't work :(

I tried the below method but didn't work.

$('something.xml').find('name').each(function() { 
    $("#news-container").append($(this).text() + "<br />");
}); 
like image 489
Sowmya Avatar asked May 07 '13 10:05

Sowmya


3 Answers

Try this:

// Load the xml file using ajax 
$.ajax({
    type: "GET",
    url: "something.xml",
    dataType: "xml",
    success: function (xml) {

        // Parse the xml file and get data
        var xmlDoc = $.parseXML(xml),
            $xml = $(xmlDoc);
        $xml.find('category[name="My t"] logo').each(function () {
            $("#news-container").append($(this).text() + "<br />");
        });
    }
});

Reference: 1. jQuery.ajax() 2. parseXML()

like image 176
palaѕн Avatar answered Nov 17 '22 08:11

palaѕн


You need to escape HTML special chars. Use this function before setting text into div.

function htmlSpecialChars(unsafe) {
    return unsafe
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;");
}
like image 3
dino.keco Avatar answered Nov 17 '22 07:11

dino.keco


-- you must call xml file first

    $.ajax({
       url: '/something.xml',
       type: "GET",
       dataType: "xml",
       success: function (result) {
            $(result).find('name').each(function () {
                $("#news-container").append($(this).text() + "<br />");
             }
           }
       });
like image 2
ahmed alnahas Avatar answered Nov 17 '22 08:11

ahmed alnahas