locked
Javascript querySelector CDATA in xml file

    Question

  • I have this path of my xml file:

    <description>
        <![CDATA[<p class="image"><img width="250" height="83" src="http://www.mydomain.com/picture/pic01.png" class="post-image" alt="Post 01 Image" title="The Demo Post" /></p>My Content
        ]]>
    </description>

    How can i select the src atribute of <img> in CDATA using querySelector (Javascript).

    Thanks!

    Wednesday, July 25, 2012 8:18 AM

Answers

  • I think applying the principles shown here should solve your problem: 
        var xml,
            $xml,
            data,
            $data,
            imgSrc;
    
        // Parse the XML using jQuery
        xml = $.parseXML('<description><![CDATA[<p class="image"><img width="250" height="83" src="http://www.mydomain.com/picture/pic01.png" class="post-image" alt="Post 01 Image" title="The Demo Post" /></p>My Content]]></description>');
    
        // Create a jQuery object from the parsed XML
        $xml = $(xml);
    
        // Select the data
        data = $xml.find('description').text();
    
        // Create a jQuery object from the data
        $data = $(data);
    
        // Select the img src attribute
        imgSrc = $data.find('img').attr('src');
    And here's a fiddle to show it working: http://jsfiddle.net/xonev/Vj4W9/.
    • Proposed as answer by soxley Wednesday, July 25, 2012 2:38 PM
    • Marked as answer by Dino He Wednesday, August 01, 2012 2:57 AM
    • Unmarked as answer by ImYuta Wednesday, August 01, 2012 3:34 AM
    • Marked as answer by ImYuta Wednesday, August 01, 2012 3:34 AM
    Wednesday, July 25, 2012 2:36 PM