无法在Jquery中获取类似XML的字符串进行解析

时间:2011-08-16 19:48:10

标签: jquery xml

我有一个这样的字符串:

<note><url>urlofpage1</url><notes>These are the Notes of Page 1</notes></note>
<note><url>urlofpage2</url><notes>These are the Notes of Page 2</notes></note>

我一直在尝试解析它,以便我可以根据网址获取笔记:

所以

notesofpage1 = getNotes('urlofpage1')

这是我尝试的一件事,但由于某种原因它不起作用。

var xml = '<note><url>urlofpage1</url><notes>These notes should load!</notes></note><note><url>urlofpage2</url><notes>These are the Notes of Page 2</notes></note>';
var $xml = $(xml);

var $notes = $xml.find('url')
                 .filter(function() { return $(this).text() == 'urlofpage1' })
                 .closest('notes');

任何想法我做错了什么?

2 个答案:

答案 0 :(得分:2)

function getNotes(urltext) {
    var notes;
    var xmlString = "<note><url>urlofpage1</url><notes>These notes should load!</notes></note><note><url>urlofpage2</url><notes>These are the Notes of Page 2</notes></note>";

    $(xmlString).find('url').each(function() {
        if ($(this).text() == urltext) {
        notes = $(this).next("notes").text();
        }
    });

   return notes;
}

var notesofpage1 = getNotes('urlofpage1');
var notesofpage2 = getNotes('urlofpage2');

alert("page 1: " + notesofpage1 + " page 2: " + notesofpage2);

http://jsfiddle.net/kqMhk/1/

答案 1 :(得分:0)

尝试将整个xml字符串包装在根元素中并调用$ .parseXML();

var xmlString  = '<root><note><url>urlofpage1</url><notes>These notes should load!</notes></note><note><url>urlofpage2</url><notes>These are the Notes of Page 2</notes></note></root>';

var xmlDoc = $.parseXML(xmlString);