【问题标题】:XML parsing issue with '&' in element text continued元素文本中带有“&”的 XML 解析问题(续)
【发布时间】:2012-08-21 13:43:05
【问题描述】:

对于中讨论的问题 XML parsing issue with '&' in element text 我遇到了同样的问题,但是在处理之前将& 替换为& 并不能解决问题

这是我的代码:

convertedString = convertedString.replaceAll("& ", "&");
convertedString = StringEscapeUtils.unescapeHtml(convertedString);

这是我的错误:

[Fatal Error] :1:253: The entity name must immediately follow the '&' in the entity reference.
org.xml.sax.SAXParseException: The entity name must immediately follow the '&' in the entity reference.
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:249)
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:284)
at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:124)

...

如果有人可以提供帮助,非常感谢

【问题讨论】:

  • 你不应该逃避&吗?你为什么要换掉它??这与您在上一个问题中遇到的问题基本相同吗??
  • 大家好,我已经更新了上面的问题,很抱歉造成混乱
  • 感谢 Keith 解决了我的问题

标签: java xml parsing


【解决方案1】:
convertedString = StringEscapeUtils.unescapeHtml(convertedString);
convertedString = convertedString.replaceAll("& ", "& "); // Also note the added space

StringEscapeUtils.unescapeHtml() 实际上会将& 转换回&

【讨论】:

    【解决方案2】:

    谢谢Arjan,对不起,这可能是一个错误的问题。我刚刚意识到这是在抱怨的 DocumentBuilder 解析器,它不接受包含 & 符号的 xml,例如:"<text> Health & Safety </text>",但是在 xml 内容中包含 & 符号是我的客户的要求,除非有其他方法可以绕过 DOMparsers,我将不得不操作前端,即 jsp 以显示 & 而不是 &

    【讨论】:

    • 所有 html 客户端都将字符串 & 显示为 &,因此您不需要为此进行任何操作。如果您允许用户输入,则必须在保存之前修复它。
    猜你喜欢
    • 2011-04-19
    • 2017-10-09
    • 1970-01-01
    • 2019-03-25
    • 1970-01-01
    • 2019-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多