使用 Java 的 DOM XML API 解析 XML 中的 & 符号
我正在尝试使用 Java DOM API(不是 SAX)解析 XML 文档。每当解析器在解析文本节点时遇到与号 (&) 时,就会出错。我猜测这可以通过 1)转义、2)编码或 3)使用不同的解析器来解决。
我正在阅读一个我无法控制的 XML 文档,因此每次阅读时我都无法准确识别 & 符号出现在文档中的位置。
我看到的类似问题的答案建议在解析 XML 时替换实体类型,但我不确定如何才能做到这一点,因为它在遇到 XML &符号时甚至不会解析。
任何帮助将不胜感激。
I am trying to parse an XML document with the Java DOM API (not SAX). Whenever the parser encounters the ampersand (&) when parsing a text node, it errors out. I am guessing that this is solvable with 1)escaping, 2) encoding or 3) Use a different parser.
I am reading an XML document that I dont have any control over, so I cannot precisely identify where the ampersand appears in the document every time I read it.
The answers I have seen to similar questions have advised replacing the entity type when parsing the XML, but I am not sure how I will be able to do that since, it doesnt even parse when it encounters the XML ampersand.
Any help will be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如前所述,XML 格式错误(哎呀!):XML 中出现的所有
&
(引入字符实体 [?] 的标记除外)都必须编码为&
。 。一些解决方案(基本上就像帖子中所描述的那样!):
对于“hack-it-up”方法,请考虑单独的输入流 - 请参阅 使用过滤器流——在实际 DOM 解析器之前作为过滤器执行: 每当遇到
&
(不是字符实体的一部分),它通过将&
插入流中来“修复它”。当然,如果 XML 源代码的基本编码不正确……祝您编码愉快。
As noted, the XML is malformed (oops!): all occurrences of
&
in XML (other than the token introducing a character entity [?]) must be encoded as&
.Some solutions (which are basically just as described in the post!):
For the "hack-it-up" approach, consider a separate input stream -- see Working with Filter Streams -- that executes as a filter prior to the actual DOM parser: whenever a
&
is encountered (that is not part of a character entity) it "fixes it" by inserting&
into the stream. Of course, if the XML source didn't get basic encoding correct...Happy coding.
“我正在阅读一个我无法控制的 XML 文档”。
不,您正在阅读非 XML 文档。收到错误的原因是,当您读取非 XML 内容时,XML 解析器需要给您一个错误。
XML 文化认为,生成格式良好的 XML 的责任在于发送者。您需要更改生成此数据的任何内容才能正确执行此操作。否则,您可能会忘记 XML 及其优点,而回到私有协议和自定义解析器的混乱世界。
"I am reading an XML document that I dont have any control over".
No, you are reading a non-XML document. The reason you get an error is that XML parsers are required to give you an error when you read something that isn't XML.
The XML culture is that responsibility for producing well-formed XML rests with the sender. You need to change whatever produces this data to do it properly. Otherwise, you might as well forget XML and its benefits, and move back to the chaotic world of privately-agreed protocols and custom parsers.