Christopher
Christopher

Reputation: 1193

get line number of xml node in js

I'm trying to validate (custom rules) a xml source. Therefore I parse the source with document.evaluate and a certain xpath and validate the result nodes. If a node is not correct, I would like to give an error with the nodes line number in the source.

How can I go about accomplishing this?

Upvotes: 1

Views: 1342

Answers (1)

amiramw
amiramw

Reputation: 21

I had similar problem and I wrote a function that finds the n-th tag on the original string based on the result of getElementsByTagName. It is something like this:

function xmlNodeToOriginalLineNumber(element, xmlRootNode, sContent) {
    var sTagName = element.tagName;
    var aNodeListByTag = xmlRootNode.getElementsByTagName(sTagName);
    var iMaxIndex = 0;
    for (var j = 0; j < aNodeListByTag.length; j++) {
        if (aNodeListByTag.item(j) === element) {
            iMaxIndex = j;
            break;
        }
    }
    var regex = new RegExp("<" + sTagName + "\\W", 'g');
    var offset = 0;
    for (var i = 0; i <= iMaxIndex; i++) {
        offset = regex.exec(sContent).index;
    }
    var line = 0;
    for (var i = 0; i < sContent.substring(0, offset).length; i++) {
        if (sContent[i] === '\n') {
            line++;
        }
    }
    return line + 1;
}

I updated your sample: https://jsfiddle.net/g113c350/3/

Upvotes: 2

Related Questions