开发者

read this xml with jquery

I'm having trouble reading this xml with jQuery.

http://jsfiddle.net/VLtqY/2/

XML:

<myElements type="AA" coID="A923">
 <element1>01</element1> 
 <element2>02</element2>
 <element3>03</element3>
</myElements>

I'm looking for the following output:

element1=01
element2=02
element3=03

A lit开发者_开发问答tle help please.


First, you need to wrap your xml variable in a call to the jQuery function, as in $(xml). Then, a call to children() will get all of your target elements.

Here's a very basic (and sloppy), working example of iterating through the elements, but it's just the selector that needs changing:

var xml = '<myElements type="AA" coID="A923"><element1>01</element1> <element2>02</element2><element3>03</element3></typeData>';

var myOutput = $("#output");

myOutput.append("=== start ===<br />");
$(xml).children().each(function () {
    var xmlnode = $(this);
    myOutput.append(this.tagName + xmlnode.text() + '<br/>');
});

myOutput.append("=== end ===");

Working demo: http://jsfiddle.net/UByfW/2/


Try this

$('*', xml).each(function () {

replacing the the line

$(xml).find("myElements").each(function () {

or

$(xml).children().each(function () {

The reason is self-explanatory: you must fetch the children, not the root element.


You can use the jQuery parseXML (see docs) function to parse the string of XML into an XML document object. Just add this line somewhere between the variable declaration and your each loop:

xml = $.parseXML(xml);

The rest of it should work fine then. You can see an example here.


I would really suggest ajax for this. IE hates the way jquery grabs the xml.I have been using this for a very long time with lots of success and no problems.

$.ajax({
    url: "path-to-file.xml",
    dataType: ($.browser.msie) ? "text" : "xml",
    success: function(data){
                            var xml;    
                            if (typeof data == "string") {
                               xml = new ActiveXObject("Microsoft.XMLDOM");
                               xml.async = false;
                               xml.loadXML(data);
                            } else {
                               xml = data;
                            }
                        alert($(xml).find('element1').text());
                                            alert($(xml).find('element2').text());
                                            alert($(xml).find('element3').text());
                    },//END SUCCSESS
    error: function(){
        alert("Sorry, There was an error loading this information. Refresh the page or try again later. ");
        history.go(-1);
    }
});//END AJAX CALL

I know this looks like a lot, but it really isn't that bad. Put your path to your xml, in the .each() do what you want to do.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜