开发者

Find an XML Node Using jQuery And Use Its Values

开发者 https://www.devze.com 2023-03-16 16:53 出处:网络
I\'开发者_如何学Gom using a XML file like this: <Test> <Unit> <Title>Test 1</Title>

I'开发者_如何学Gom 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


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.


$("#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")


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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消