18

I have a server that response the request with XML, I want to parse it in the javascript. I really like the actionscript xml parser that is really easy for me to use. I am wandering is there a very easy/straightforward way to parse the XML I fetched from server?

The ideal usage should be:

fetchXML new XMLParser. parser.parse access the document.

btw I plan to use jquery.

2 Answers 2

23

A regular $.ajax with dataType: "xml" will do the trick, then you can browse the contents with jQuery selectors like you would a simple web page (e.g. the attr function in the example to retrieve the "code" field of each book node or the find function to find specific node types).

For example, you could do this to find a specific book by title:

$(xml).find("book[title='Cinderella']")

where xml is the data the success handler receives from $.ajax.


Here is the complete example:

<!DOCTYPE html>
<html>
<head>
 <title>jQuery and XML</title>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <meta name="language" content="en" />
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body

<div id="output"></div>

<script type="text/javascript">
$(document).ready(function(){
 $.ajax({
  type: "GET",
  dataType: "xml",
  url: "example.xml",
  success: function(xml){
   $(xml).find("book").each(function(){
    $("#output").append($(this).attr("code") + "<br />");
   });
  }
 });
});
</script>


</body>
</html>

And a matching XML file:

<?xml version="1.0" encoding="UTF-8"?> 
<books title="A list of books">
 <book code="abcdef" />
 <book code="ghijklm">
  Some text contents
 </book>
</books>
5
  • Thanks! If I don't want to find and the result only contains "<book code="kdjfkjd" /> how I can reference the "book" element?
    – Bin Chen
    Oct 18, 2010 at 10:07
  • 1
    $(xml).find("book") gives you a list of the book nodes. In the "each" loop, $(this) is a reference to the book node.
    – wildpeaks
    Oct 18, 2010 at 10:15
  • yes but for my code I don't want the find because it's unnecessary, i only have one book element, is it possible to reference it directly without find?
    – Bin Chen
    Oct 18, 2010 at 10:16
  • If you have only one node, then you can directly use the result of $(xml).find("book"), like $(xml).find("book").attr('code')
    – wildpeaks
    Oct 18, 2010 at 10:17
  • Otherwise, $(xml).children() is an alternative if you don't like the find method
    – wildpeaks
    Oct 18, 2010 at 10:18
3

Return the data with the right content type (e.g. application/xml) and XHR will parse it for you.

See also: the dataType argument for jQuery's ajax method.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.