[英]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". 我在网页上有一组按钮标签,并且我想获取一个其innerText为“保存”的特定按钮标签。 (It has no id to it.) So I have this code (它没有ID。)所以我有这段代码
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. 当我在chrome控制台中尝试时,它可以完美工作。 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.) 但是我不能在我的果冻文件中包含它(这是一个将被处理成html的xml标记;类似于jsp。)
The problem is with the "<" operator in the for loop which is causing this 问题是for循环中的“ <”运算符导致了
SAXParserException: "The content of elements must consist of well-formed character data or markup." SAXParserException:“元素的内容必须包含格式正确的字符数据或标记。”
And I learnt not to use for..in loops with arrays. 而且我学会了不要在数组中使用for..in循环。 What can I do? 我能做什么? Please suggest me some workaround. 请建议我一些解决方法。
You are solving the wrong problem. 您正在解决错误的问题。 Your problem is "Including a <
character in XML breaks the XML". 您的问题是“在XML中包含<
字符会破坏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. 无需避免标准的for循环。
Either wrap that section with CDATA markers (which stop XML special characters (except the end of CDATA sequence) being special) or represent the <
with <
任一包装与CDATA标记,其部分(其停止XML特殊字符(除CDATA序列的末端)是特殊)或代表<
用<
in the XML. 在XML中。
<![CDATA[
for (var i = 0; i < j; i++) {
etc(i);
}
]]>
or 要么
for (var i = 0; i < j; i++) {
etc(i);
}
You can iterate with the new Array.forEach
method, but it's available from JavaScript 1.6 only: 您可以使用新的Array.forEach
方法进行迭代,但仅JavaScript 1.6可用:
var tags = Array.prototype.slice.call(document.getElementsByTagName("button"));
tags.forEach(function (tag) {
// ...
});
But the real solution would be to put your code into <![CDATA[]]>
: 但是真正的解决方案是将您的代码放入<![CDATA[]]>
:
<code>
<![CDATA[
var tags = document.getElementsByTagName("button");
for (var i = 0; i < tags.length; i++) {
// ...
}
]]>
</code>
var limit = tags.length;
//loop until 0 (which is false)
while(limit) {
if (tags[tags.length-limit].innerText === 'Save') {
tags[tags.length-limit].click();
break;
}
limit--;
}
Put it inside <[CDATA[ ... ]]>
将其放入<[CDATA[ ... ]]>
Editing: Wrong syntax... 编辑:语法错误...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.