简体   繁体   中英

Unexpected token ILLEGAL when load xml object?

A seesion from database and marshal to String

String xml = XMLUtils.marshallToString(list);
sre.getServletRequest().setAttribute("LIST", xml);

and code JS

var regObject = '${requestScope.LIST}';

..... when open in browser. View source i have error Unexpected token ILLEGAL.

  var regObject = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>//Unexpected token ILLEGAL <items> <item> <id>ID</id> <productName>PrdName</productName> <productLink>LINK</productLink> <productImage>IMG</productImage> </item> </items>'; 
code marshalToString:

 JAXBContext jaxb = JAXBContext.newInstance(List.class); Marshaller mar = jaxb.createMarshaller(); mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); mar.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); StringWriter sw = new StringWriter(); mar.marshal(items, sw); return sw.toString(); 

Anyone know how to fix this problem?

JavaScript's ' and " string literals can't have unescaped newlines in them, hence the error you're getting. (ES2015's backtick template strings can.)

When outputting the XML, you'll want to ensure that any character that may be special inside a JavaScript string literal, such as ' (because you're using single quotes), newlines, and backslashes, are escaped with a backslash in front of them.

Eg, you want your output to look like this:

var regObject = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\
<items>\
    <item>\
        <id>ID</id>\
        <productName>PrdName</productName>\
        <productLink>LINK</productLink>\
        <productImage>IMG</productImage>\
        <something>I\'m an example with an apostrophe</productImage>\
        <something>I\'m an example with a \\ (backslash)</productImage>\
    </item>\
</items>';

Or of course, replace newlines with \\n ( after escaping any existing backslashes):

var regObject = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n<items>\n<item>\n<id>ID</id>\n<productName>PrdName</productName>\n<productLink>LINK</productLink>\n<productImage>IMG</productImage>\n<something>I\'m an example with an apostrophe</productImage>\n<something>I\'m an example with a \\ (backslash)</productImage>\n</item>\n</items>';

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM