4

I'm using a XML file like this:

<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 on the XML document for a <Title> given and get its entire <Unit>, so I can work with the 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've been using this as the base of my XML reading

1
  • This is confusing. You have XML and HTML in your question. What goes where? Where does the Javascript go? Where are you searching for any particular Title? Your function doesn't even accept a parameter to make that work. How are your HTML and XML documents related? Commented Jul 1, 2011 at 23:35

3 Answers 3

4

Is this what you're looking for? Click Here (jsFiddle link)

In that code you'll have to get the XML and store it in a variable first like i did. The code may not be exactly what you're looking for but it may be a good starting point. Play with the code and let me know if this is what you're looking for or not.

You could also try this (same code as jsFiddle link but just using alerts instead of appending the 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);
    }
});

That should give you two alerts.

Sign up to request clarification or add additional context in comments.

Comments

2

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

To select all Unit element use $("Unit")

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

1 Comment

check out my answer and see if that's what you're looking for. $("Unit") will return [] because it is returning the object not the actual values. you could access the values by adding .text() at the end of $("Unit").
1

The selector #Unit looks for nodes with an id attribute equal to "Unit".

You need the selector Unit, which looks for Unit nodes.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.