加载xml对象时出现意外的标记ILLEGAL

Unexpected token ILLEGAL when load xml object?

本文关键字:ILLEGAL 意外 xml 对象 加载      更新时间:2023-09-26

从数据库到字符串的转换

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

和代码JS

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

当在浏览器中打开时。查看源代码我有错误意外的令牌非法。

    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>';
代码marshaleToString:

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();

有人知道如何解决这个问题吗?

JavaScript的'"字符串文字中不能有未加注释的换行符,因此会出现错误。(ES2015的回溯模板字符串可以。)

在输出XML时,您需要确保JavaScript字符串文字中任何可能特殊的字符,如'(因为您使用的是单引号)、换行符和反斜杠,都是前面带有反斜杠的转义符

例如,你希望你的输出看起来像这样:

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>';

当然,也可以用'n替换换行符(转义任何现有反斜杠后的):

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>';