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). Now the statement 2 will put the value of the jsp variable xmlContent to the javascript variable 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).
I must say that the xml file contains both single and double quotes inside it and also it contains entities like &***;
. Now why the third statment returns 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 ?
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. Remember that on the Javascript side, it's like typing a literal string. If your XML contains new-lines, it's like splitting your literal string in multiple lines.
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. This will also work correctly if you have any CDATA sections in your XML with newlines you wish to keep. Some code:
xmlContent = xmlContent.replace("\n", "\\\n").replace("\r\n", "\\\r\n");
If you know the XML schema (XSD, and it does not change) I suggest you to use JAXB . You may implement a servlet which handles the XML file and returns a bean to the JSP.
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.