简体   繁体   中英

Jquery: Count node separation in xml

I'm loading an xml document using JavaScript (Jquery $.ajax ).

I need to be able to count the number of branches (b) separating 2 text nodes (s).

Eg

    <b n="Archaea">
        <s>Archaea</s>
        <b n="Eubacteria">
            <s>Cyanobacteria</s>
            <s>Spirochaete</s>
            <b n="Seaweeds">
                <s>Red rags</s>
                <s>Calliblepharis</s>
            </b>
        </b>
        <b n="Land plants">
            <s>Liverwort</s>
            <s>Moss</s>
            <s>Bracken fern</s>
            <b n="Seed plants">
                <s>Scots pine</s>
                <s>Ginko</s>
                <s>Welwitschia</s>
            </b>
        </b>
    </b>

So, how many branches is 'Scots pine' away from 'Calliblepharis', for example. In this case, the answer would be 4 (Seed plants > Land plants > Archaea > Eubacteria > Seaweeds).

I also need to calculate the 'closest common ancestor' between 2 elements. For example, between 'Scots pine' and 'Ginko' it would be 'Bracken fern' (because Bracken fern is the closest species to the branch that contains 'Scots pine' and 'Ginko'). I'm really not sure how this would work when the 2 elements are very far from each other in different branches.

Sorry if I'm using the wrong language here. Hope it makes sense.

Sorry about the late reply.

I've set up aa demo at jsbin

Hopefully it's fairly self explanatory but if not ask me.

For the xhr bit you need to have an file.xml in the same directory as the page.

This is the main function that gets the distance between the branches

    function elementDistance(elem1, elem2) {
        var steps = 0;
        //the parent elements are the branches
        var first = elem1.parentElement;
        var second = elem2.parentElement;
        //if the elements are at different depths you need to even them up
        //and count each time as a step
        if (elem1.depth() > elem2.depth()) {
            while (first.depth() > second.depth()) {
                first = first.parentElement;
                steps++;
            }
        }
        else if (elem1.depth() < elem2.depth()) {
            while (first.depth() < second.depth()) {
                second = second.parentElement;
                steps++;
            }
        }
        while (first !== second) {
            steps += 2;
            first = first.parentElement;
            second = second.parentElement;
        }
        return steps;
    }

ps the demo doesn't work in firefox or IE

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