Amr Elgarhy
Amr Elgarhy

Reputation: 68912

How to read and parse an XML which exist inside the page using jQuery

I have an xml file which I imported in my html page like this:

<script type="text/xml" src="Categories.xml" id="categoriesXML">  
</script>

And using my jQuery code I want to read this xml file and parse it to do some stuff with its data, so I tried to write something like this:

 var xml = $('#categoriesXML').text();
    $(xml).find("Category").each(function () {
        alert($(this).find("Title").text());
    });

But what I got is that the xml variable is empty.

I also tried to write it:

var xml = $('#categoriesXML');

but again I can't get it work.

The xml file content:

<?xml version="1.0" encoding="utf-8" ?>
<Categories>
  <Category>
    <Title>CAT1</Title>
    <SubCategories>
      <SubCategory>
        <Title>SUB1</Title>
      </SubCategory>
    </SubCategories>
  </Category>
</Categories>

So how to read this xml file this way, without using ajax?

Why I want it without ajax:
Because I want this to happen on the page load, and no need to start getting the file after my page loads which will show my page nearly empty at first load, and will wait till the ajax response with the file which may be very big in some cases.

Upvotes: 0

Views: 578

Answers (4)

Amr Elgarhy
Amr Elgarhy

Reputation: 68912

I will write some server side code to render the xml content directly on the page to be as in this sample: http://jsfiddle.net/Cq8Fu/ and like that It will work, because using an external file It will not work and as @Capsule said in his comments above, there will be a delay to load the file and this work around is useless and will not save time at all.

By the way this sample I got from an answer someone answered here but he deleted his answer later "don't know why".

Upvotes: 0

brianpeiris
brianpeiris

Reputation: 10795

Use a synchronous AJAX request at the top of the page to populate your JavaScript variable. It will mimic the inline XML.

Upvotes: 1

kobe
kobe

Reputation: 15835

I don't think it will work that way , you should probably load it document.ready through ajax and start processing it.

Make an ajax call in the document.ready

$(document).ready(function() {

   // make ajax call and populate xml and process the xml.


});

Upvotes: 1

Ron Harlev
Ron Harlev

Reputation: 16673

I think you will need to load the XML with AJAX.
Here is a summary of the way to do it

Upvotes: 1

Related Questions