简体   繁体   中英

How can I find a specific subnode in XML with jQuery selectors/filters?

I have this XML of game modes:

<?xml version="1.0" ?>
<gameType>
<easy>
    <numberOfLevels>2</numberOfLevels>
    <levelGroup id="1">
        <level id="1">[0]</level>
        <level id="2">[1]</level>
        <level id="3">[2,2]</level>
    </levelGroup>
    <levelGroup id="2">
        <level id="1">[0]</level>
        <level id="2">[1]</level>
        <level id="3">[3,2]</level>
    </levelGroup>
</easy>
<medium>
    <numberOfLevels>1</numberOfLevels>
    <levelGroup id="1">
        <level id="1">[0,2]</level>
        <level id="2">[1,4]</level>
        <level id="3">[2,5,6]</level>
    </levelGroup>
</medium>

What I want to do is get all levels for the appropriate game mode. For example:

//we get the list of all games
var xmlDoc = $(xml);
//we get number of levels for the selected game mode, default gameMode = 'easy'
var games = xmlDoc.find(gameMode).find("numberOfLevels")[0].textContent;
//we select a game by choosing a random number
var selectedGameIndex = $.random(games);
//Here I want to filter out only the appropriate elements, eg, in the default
//game mode and with the selectedGameIndex set to '1', I want to return an
//array that contains only the values, 
//eg. var resultArray = [[0],[1]....[2,11,12]]; What I got is this:

var elements = sandbox.baseLib.$(gameMode + " > levelGroup[id='"
    + selectedGameIndex + "']", xmlDoc).children();
 var predefinedIndexSequence = elements.map(function() {
    return sandbox.baseLib.$(this).text();
}).get();

gameLength = gameSequence.size();

Edit: This is the correct code (at least for what I need it). The mistake was in trying to filter xmlDoc when I didn't actually need the result from the filter, I needed the array made from "elements" variable.

You can abbreviate the last chunk of your code (from var levelsArray onward) by using .map() :

return elementsArray.map(function() {
    return $(this).text();
});

...although I would call it $elements instead of elementsArray because it appears it's actually a jQuery object, not a true array. If I'm wrong and it's not a jQuery object, do this instead:

return $.map(elementsArray,function(el,i) {
    return el.textContent;
});

You can also replace var games = xmlDoc.find(gameMode).find("numberOfLevels")[0].textContent with var games = xmlDoc.find(gameMode).find("numberOfLevels:eq(0)").text() , although that's not much shorter, just more jQuery-like.

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