Amani Ben Azzouz
Amani Ben Azzouz

Reputation: 2565

parse xml data with jquery

I want to parse an xml file given as a php variable with the use of jquery: jQuery.parseXML()

This is my file content:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<?php
  $xml="<rss version='2.0'><channel><title>RSS Title</title></channel></rss>";
?>
<p id="someElement"></p>
<p id="anotherElement"></p>
<script>
  var xml = "<?php echo $xml; ?>",
  xmlDoc = $.parseXML( xml ),
  $xml = $( xmlDoc ),
  $title = $xml.find( "title" );
  $( "#someElement" ).append( $title.text() );
  $title.text( "XML Title" );
  $( "#anotherElement" ).append( $title.text() );
</script>
</body>
</html>

but what if my xml variable is like this:

$xml ='<?xml version="1.0" encoding="UTF-8" ?>
<data request-id="ID">
<data name="Name1"
    d1="0"
    d2="0231234"
    d3="32584">
    <data name="Name2"
        d4="231234"
        d5="2012-06-06 18:18:10.000607"
        d6="3b048653-aaa9-485b-b0dd-d16e068230e9" />
    </data>
</data>';

how to display for example d1 or d4?

Upvotes: 1

Views: 226

Answers (1)

Daniel Gasser
Daniel Gasser

Reputation: 5133

Look with the following jQuery selector '[attr="somevalue"]' and the method find() in the correct node, then use the method attr():

$(document).ready(function(){
    var xml ='<?xml version="1.0" encoding="UTF-8" ?><data request-id="ID">' + 
        '<data name="Name1" d1="0" d2="0231234" d3="32584">' + 
            '<data name="Name2" d4="231234" d5="2012-06-06 18:18:10.000607" d6="3b048653-aaa9-485b-b0dd-d16e068230e9" />' +
            '</data>' +
        '</data>' +
        '</data>',
       d1 = $(xml).find('data[name="Name1"]').attr('d1'),
       d4 = $(xml).find('data[name="Name2"]').attr('d4');
    document.write('d1: ' + d1);
    document.write('<br>');
    document.write('d4: ' + d4);
    window.console.dirxml($(xml));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

Upvotes: 1

Related Questions