使用 Woodstox 解析器解析“&”字符时出错

问题描述 投票:0回答:1

Java:1.6
伍德斯托克斯:4.1.4

我目前正在尝试让 Woodstox xml 解析器成为我的朋友。但开始真的很难:) 我有一个小的?像这样解析 xml 时出现问题:

<teams>
    <team id="team1">Mom & Dad</team>
    <team id="team2">Son & Daughter</team>
</teams>

很简单,但不幸的是我遇到了这个异常:

Exception in thread "main" [com.ctc.wstx.exc.WstxLazyException] com.ctc.wstx.exc.WstxUnexpectedCharException: Unexpected character ' ' (code 32) (missing name?)
 at [row,col {unknown-source}]: [2,24]

发生这种情况是因为性格 &。

是否可以成功读取xml而不出现此异常?

java xml xml-parsing woodstox
1个回答
10
投票

&
是无效字符,应该转义为
&amp;
或包含在 CDATA 部分中。

<teams>
    <team id="team1">Mom &amp; Dad</team>
    <team id="team2"><![CDATA[Son & Daughter]]></team>
</teams>

来自:http://www.w3.org/TR/REC-xml/#syntax

与号 (&) 和左尖括号 (<) MUST NOT appear in their literal form, except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section. If they are needed elsewhere, they MUST be escaped using either numeric character references or the strings "

&amp;
" 和 "
&lt;
" 分别。

© www.soinside.com 2019 - 2024. All rights reserved.