[英]Loading xml as string and using in jsp and javascript
I have the codes below. 我有下面的代码。 Statement 1 loads an xml file of average size (~300-400KB) and stores the content into a string variable (xmlContent).
语句1加载平均大小(〜300-400KB)的xml文件,并将内容存储到字符串变量(xmlContent)中。 Now the statement 2 will put the value of the jsp variable xmlContent to the javascript variable xmlText.
现在,语句2将把jsp变量xmlContent的值放入javascript变量xmlText中。 The statement 3 will try to create an XMLDocument object in javascript (load string as xml document so that it can be parsed through DOM methods).
语句3将尝试在javascript中创建XMLDocument对象(将字符串作为xml文档加载,以便可以通过DOM方法进行解析)。
I must say that the xml file contains both single and double quotes inside it and also it contains entities like &***;
我必须说xml文件在其中包含单引号和双引号,并且还包含
&***;
实体&***;
. 。 Now why the third statment returns null?
现在为什么第三条语句返回null? can somebody explain?
有人可以解释吗?
Can somebody tell me some better way to transfer the xml string data like by performing some encoding/decoding or by escaping ? 有人可以告诉我一些更好的方式来传输xml字符串数据,例如通过执行一些编码/解码或转义吗?
Thanks. 谢谢。
<%
String xmlContent = FileReader.readFile("/xml/books.xml");
%>
<script type="text/javascript">
var xmlText = ' <% =xmlContent %> ';
new DOMParser().parseFromString(xmlText, "text/xml");
//I know that it will not work in IE
</script>
If your XML contains new-line characters (LF / CRLF) you will need to remove them or escape them in the Java code before passing it to the Javascript code. 如果您的XML包含换行符(LF / CRLF),则需要先将其删除或在Java代码中对其进行转义,然后再将其传递给Javascript代码。 Remember that on the Javascript side, it's like typing a literal string.
请记住,在Javascript方面,这就像键入文字字符串一样。 If your XML contains new-lines, it's like splitting your literal string in multiple lines.
如果您的XML包含换行符,则就像将文字字符串分成多行一样。
Safer bet is to search-and-replace new-lines in your XML with backslash-newline to escape the newlines in Javascript and effectively provide a multi-line Javascript string. 更好的选择是使用反斜杠换行符搜索和替换XML中的换行符,以转义Javascript中的换行符并有效地提供多行Javascript字符串。 This will also work correctly if you have any CDATA sections in your XML with newlines you wish to keep.
如果您的XML中有希望保留的换行符,那么CDATA部分也将正确运行。 Some code:
一些代码:
xmlContent = xmlContent.replace("\n", "\\\n").replace("\r\n", "\\\r\n");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.