1

次の例の「Books」などの要素名を使用せずにXML要素を読み取ろうとしています。例えば

  <Books>
           <book>
              <title>C++</title>
              <author>A</author>
           </book>
           <book>
              <title>XML</title>
              <author>X</author>
           </book>
    </Books>

言い換えると、HTMLのjqueryを使用して、「Books」要素を動的に読み取り、子要素を配列に割り当てる方法です。どんな助けでもいただければ幸いです。

4

2 に答える 2

1

私はあなたのために簡単な HTML を書きました。http://jsfiddle.net/UC2dM/185/のデモ

$.ajax({
    url:'/echo/xml/',
    data: {xml:'<Books><book><title>C++</title><author>A</author> </book><book><title>XML</title><author>X</author></book></Books>'},
    dataType: 'xml',
    type:'post',
    success: function(data){
        var xml = $(data);
        $('#container').append( CategoryToUl(xml.children()) );
    }
});

function CategoryToUl(xml){
    var categories = xml.children('book');
    if (categories.length > 0)
    {
        var ul = $('<ul/>');
        categories.each(function(){
            var $this = $(this);
            var li = $('<li/>');
            var a = $('<a/>',{
                text: $this.children('title').text()
            });
            li.append(a);
            li.append( CategoryToUl( $this ) );
            ul.append(li);
        });
        return ul;
    }
    return null;
}
于 2013-02-18T17:47:59.677 に答える
0

皆さん、ありがとうございました。私は自分の解決策を見つけました

var xml = "<root><stuff></stuff><stuff><stuffchild></stuffchild></stuff></root>";

function alertit(jqueryObject) {
    if (jqueryObject.length === 0) return;

    jqueryObject.each(function() {
        alert(this.nodeName.toLowerCase());
    });

    alertit(jqueryObject.children());
}

alertit($(xml));

http://jsfiddle.net/TBwm8/3/

ありがとう。

于 2013-02-18T18:37:38.090 に答える