Vinc199789
Vinc199789

Reputation: 1046

Why is Jquery parseXML not working?

I am new to xml and I am trying to search through a xml file using JQuery parseXML(). I made the code below to search for the <name> tags in the xml file and output each name it's value.

When I run the code I get these 2 errors:

  syntaxisfout         
  index.html:1:1

  Error: Invalid XML: test.xml    
  jquery.min.js:2:1820

I used this tutorial: http://api.jquery.com/jQuery.parseXML/

This is the xml file Structure I use:

<store>
  <product>
      <name>product name</name>
      <price>price</price>
      <platform>platform</platform>
  </product>
</store>

This is the JQuery code I use:

xmlDoc = $.parseXML( 'test.xml' ); //path to xml file
$xml = $( xmlDoc );
$name = $xml.find( "name" );

$(document).each(function(){
    $('body').append('<p>'+ name + '</p>');
});

Can somebody tell what I am doing wrong?

Upvotes: 1

Views: 4040

Answers (1)

prodigitalson
prodigitalson

Reputation: 60413

The problem is you are using a filename as your xml parameter. There is no facility within $.parseXML to parse a file. It parses an XML string. If you need to load XML from a separate file you will need to ajax it in or otherwise load the filecontents into a js variable:

xmlStr = '<store>'
 + ' <product>'
 + '    <name>product name</name>'
 + '     <price>price</price>'
 + '     <platform>platform</platform>'
 + ' </product>'
 + '</store>';

xmlDoc = $.parseXML(xmlStr);
$xml = $(xml);
// do stuff

With ajax:

$.ajax({
     url: 'url/for/text.xml',
     dataType: 'xml'
}).done(function (xmlDoc) {
    $xml = $(xmlDoc);
    // do stuff
});

Upvotes: 2

Related Questions