开发者

How to get the desired XML portion into variables with JQuery/Javascript?

开发者 https://www.devze.com 2023-03-20 13:30 出处:网络
Assuming 开发者_开发技巧I have the following example XML: <PrimaryMembers> <Member> <Name>Jessica</Name>

Assuming 开发者_开发技巧I have the following example XML:

<PrimaryMembers>
<Member>
<Name>Jessica</Name>
<Hobby>Softball</Hobby>
</Member>
<SecondaryMembers>
<Member>
<Name>Wilson</Name>
<Hobby>Baseball</Hobby>
</Member>
<Member>
<Name>John</Name>
<Hobby>Soccer</Hobby>
</Member>
</SecondaryMembers>
</PrimaryMembers>

With JQuery, I want to be able to get JUST:

<Name>Jessica</Name>
<Hobby>Softball</Hobby>

into a name and hobby variable.

Assume that the string containing the xml is stored in a variable xml. How do I do this? I notice that every time I try to store just Jessica into a variable, it stores "JessicaWilsonJohn" into it.

I imagine it has to do with the

var name = $(xml).find("Something").text();

NOTE: I do NOT want to store Wilson and John. I only want to get just Jessica and Softball.


var members = [];
$(xml).find('Name:contains(Jessica)').each(function(){
  var member = {};
  $(this).siblings().each(function(){
    member[this.nodeName] = $(this).text();
 });
  members.push(member);
});

However it looks like your XML has soem issues if its an accurate representation. The PrimaryMembers is missing a closing tag. Also, while not a deal breaker it seems that each Name/Hobby should be contained by a Member element, which is not the case across the document.

NOTE: I do NOT want to store Wilson and John. I only want to get just Jessica and Softball.

Well youre actually making a bad presumption here. There is no guarantee that "Jessica" will be unique so you may not have only one result. With that said you could do the following:

function getMember(memberName){
 var properties = {};
 $(xml).find('Name:contains("'+memberName+'")').siblings().each(function(){
    properties[this.nodeName] = $(this).text();
 });
 return properties;
};

var theMember = getMember('Jessica');
0

精彩评论

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