문제

Consider this XML snippet:

 <book id="5" />
 <book id="15" />
 <book id="5" />
 <book id="25" />
 <book id="35" />
 <book id="5" />

How can I compose an E4X statement/query to get a list of the unique values in the id attribute? I'm using E4X in a JavaScript non-browser context.

5
15
25
35

Is there a distinct() or groupby() method of any kind that would help? If not, how could this be accomplished?

도움이 되었습니까?

해결책

There is no unique or groupby method. However, E4X allow you to quickly create an XMLList of the values non-unique values.

var xmlSnippet = <stuff><book id="5"/>
                        <book id="15"/>
                        <book id="5"/>
                        <book id="25"/>
                        <book id="35"/>
                        <book id="5"/>
                  </stuff>;
var attributes = xmlSnippet['book'].attribute("id");

To make it unique, you can then take the XMLList, iterate through it, and store each element as the key value in an object.

var uniqueAttributes = new Object ();

for each (var a in attributes)
{
    uniqueAttributes[a] = null;
}

To access these values, iterate through them using a for in loop (not a for each in)

for (var u in uniqueAttributes)
{
// do something with u
}

다른 팁

This presumes the attribute values in question do not contain a pipe, "|", character. If so then change the pipe character at the very bottom to something else not in the values. The variables are statically typed for JIT execution. Hope this does what you need.

var idvalues = function (x) { //x = node name
    var a = document.getElementsByTagName(x),
        b,
        c = [],
        d,
        e;
    for (b = a.length - 1; b > -1; b -= 1) { // gather all the id values into an array
        c.push(a[b].getAttribute("id"));
    }
    for (b = c.length - 1; b > -1; b -= 1) {
        if (c[b] !== "") {
            for (d = b - 1; d > -1; d -=1) {
                if (c[b] === c[d]) {
                    c[d] = "";
                }
            }
        }
    }
    e = c.join("|");
    c = e.split("|");
    return c;
};
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top