Search code examples
javascriptxmlfor-loopiterationmarkup

Escape special characters in XML documents


I have a set of button tags on a webpage and I want to get one particular button tag whose innerText is "Save". (It has no id to it.) So I have this code

var tags = document.getElementsByTagName("button");
for (var i = 0; i < tags.length; i++) {
    if (tags[i].innerText === 'Save') {
        tags[i].click();
        break;
    }
}

which works perfectly when I try it in chrome console. But I can't include this in my jelly file(which is an xml markup that will be processed into html; something like a jsp.)

The problem is with the "<" operator in the for loop which is causing this

SAXParserException: "The content of elements must consist of well-formed character data or markup."

And I learnt not to use for..in loops with arrays. What can I do? Please suggest me some workaround.


Solution

  • You are solving the wrong problem. Your problem is "Including a < character in XML breaks the XML". You need to find out how to include such a character correctly, not avoid having one ever appear in your data. There is no need to avoid a standard for loop.

    Either wrap that section with CDATA markers (which stop XML special characters (except the end of CDATA sequence) being special) or represent the < with &lt; in the XML.

    <![CDATA[
    for (var i = 0; i < j; i++) {
        etc(i);
    }
    ]]>
    

    or

    for (var i = 0; i &lt; j; i++) {
        etc(i);
    }