开发者

Parsing an HTML like String in Javascript or JQuery

So I have a string like this

string = "<user>username 1<notes>Notes of User 1</notes></user> <user>username 2<notes>Notes of User 2</notes></user>"

How开发者_如何学Python could I parse the string in Javascript or JQuery to pull out the "Notes" of either user 1 or user 2.

So I'll have a variable like this:

variable = user;

printout notes of user.


You mean an XML like string, not a HTML like string. jQuery has a lovely XML parser for that http://api.jquery.com/jQuery.parseXML/


to identify the notes of user1 or user2 you need to change your xml a bit

string = "<user>username 1<notes id='user1'>Notes of User 1</notes></user> <user>username 2<notes>Notes of User 2</notes></user>"

notice that i added id=user1

alert($(string).find("notes[id='user1']").text());

here is the fiddle http://jsfiddle.net/Qa5sP/


EDIT after the -1 :(

No, jQuery selectors do not parse XML. This may appear to work at times, but it's invalid and browser-dependent.

So, here is the parseXML way:

 xmlDoc = $.parseXML(string),
    $xml = $(xmlDoc),
    $title = $xml.find("notes[id='user1']").text();

alert($title); 

Live demo.


Here's a JSFiddle. It's simple to do using jQuery if you are using HTML-parsible XML (as seen above).

 string = "<user>username 1<notes>Notes of User 1</notes></user> <user>username 2<notes>Notes of User 2</notes></user>";
 var node = $("<div>" + string + "</div>");

 alert(node.find('notes').text());
 node.attachTo(document.body); //append to dom?


I would rather go with this approach.

var xml = "<user>username 1<notes>Notes of User 1</notes></user> <user>username 2<notes>Notes of User 2</notes></user>";

function FindNotesByUserName(uName) {
    var node = $('<div/>').html(xml);
    return node.find(":contains('" + uName + "')").closest("user").find("notes").text();
}

var desiredNotes = FindNotesByUserName("username 2");

N.B: This is a minor alteration of what ghayes did. Just to meet OP requirement.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜