Find XML Node Using jQuery and Use Its Values

I am using an XML file as follows:

<Test> <Unit> <Title>Test 1</Title> <Date>01/07/2011</Date> <Content format="html"><![CDATA[Here goes some content]]></Content> </Unit> <Unit> <Title>Testing New XML</Title> <Date>27/06/2011</Date> <Content format="html"><![CDATA[Here goes some content]]></Content> </Unit> <!-- A lot of stuff like this --> </Test> 

I want to use jQuery to search the XML document for <Title> and get it all <Unit> , so I can work with values ​​like this:

 function append(title, date, content) { $("#Unit").append("<h1 id='title'><b>" + title + "</b></h1><h2 id='date'>" + date + "</h2><p>" + content + "</p>"); } 

How can i do this?

PS: I used this as the basis of my XML reading

+4
source share
3 answers

Is this what you are looking for? Click here (jsFiddle link)

In this code, you will need to get the XML and save it in a variable first, like me. The code may not be exactly what you are looking for, but it can be a good starting point. Play with the code and let me know if this is what you are looking for or not.

You can also try this (same code as jsFiddle link, but just using warnings instead of adding data to the DOM)

 var xml = "<Test><Unit><Title>Test 1</Title><Date>01/07/2011</Date><Content format='html'>some content here</Content></Unit><Unit><Title>Testing New XML</Title><Date>27/06/2011</Date><Content format='html'>some more content here</Content></Unit></Test>"; $(xml).find("Unit").each(function(){ if($(this).find("Title").length > 0){ var unitData = $(this).text(); alert(unitData); } }); 

This should give you two warnings.

+4
source

$("#Unit") selects all elements with the identifier "unit".

To select all Unit elements, use $("Unit")

Edit: if you have a Title element in a variable, you can get Unit with $(myTestVariable).closest("Unit")

+2
source

The #Unit selector #Unit for nodes with an id attribute of "Unit" .

You need a Unit selector that searches for Unit nodes.

+1
source

All Articles