简体   繁体   中英

How do I parse and search xml for a specific node value then have access to other child nodes?

Im using the following code to search a local xml source and Im trying to...

1.) search / filter for the player xml node where the findplayername variable matches the playername attribute OR the name node in the XML (I can change the xml source nodes / attributes however I want if that helps)

2.) then be able to write out / access the node values for the other nodes such as id and twid that correspond to the findplayername match -- if that makes any sense.

Im not sure how the loop and function should loo, but heres what I've tried... can anyone shed any light on this for me?

function getTwitterID(findplayername){
$.ajax({
    type: "GET",
    url: "myxmlfile.xml",
    dataType: "xml",
    success: function(xml) {

            $(data.player).each(function (i, item) {

        $(xml).find("name").text() == findplayername;
        });
           }
});
 };

My returned XML looks like this:

<players>
    <player playername="Jim Smith">
      <id>1</id>
      <name>Jim Smith</name>
      <twid>abc</twitterid>
    </player>
    <player playername="Jane Doe">
      <id>2</id>
      <name>Jane Doe</name>
      <twid>xyz</twitterid>
    </player>
</players>

EDIT -- this worked perfectly thanks @Ohgodwhy:

function getTwitterID(findplayername){
$.ajax({
    type: "GET",
    url: "myxmlfile.xml"",
    dataType: "xml",
    success: function(xml) {

        $(xml).find('player').each(function(i, item){
            if($(this).find('name').text() == findplayername){
                console.log($(this).find('twid').text());
            }
        });
    }
});

};

I'm not sure if it's just a bad copy-pasta or if you've legitimately declared your variables wrong, but it should be :

$(xml).find('player').each(function(){
    $(xml).find('name').text(findplayername);
});

Observe the above,y ou also can't use jQuery as a getter and a setter but rather need to pass your value to the function as an argument so it can be evaluated. Unless I'm wrong about the above and meant to do a comparison of course:

$(xml).find('player').each(function(){
    if($(this).find('name').text() == findplayername)){
        //do something
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM