【问题标题】:Unexpected token ILLEGAL when load xml object?加载 xml 对象时出现意外的令牌非法?
【发布时间】:2015-11-29 20:06:10
【问题描述】:

从数据库和编组到字符串的视图

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

和代码JS

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

..... 在浏览器中打开时。查看源代码我有错误 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>';
代码编组字符串:
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 java xml session


    【解决方案1】:

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

    【讨论】:

    • 如何将 2 行 mar.setProperty() 设置为您所说的格式?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多