Java,XML DocumentBuilder - 解析时设置编码
我正在尝试保存一棵树(扩展JTree
),该树将XML
文档保存为已更改其结构的DOM对象
。
我创建了一个新的文档对象,遍历树以成功检索内容(包括 XML
文档的原始编码),现在有一个包含树的 ByteArrayInputStream
具有正确编码的内容(XML
文档)。
问题是当我解析 ByteArrayInputStream 时,编码会自动更改为 UTF-8 (在 XML 文档中)。
有没有办法防止这种情况并使用 ByteArrayInputStream 中提供的正确编码。
还值得补充的是,我已经使用过transformer.setOutputProperty(OutputKeys.ENCODING,encoding)
方法来检索正确的编码。
任何帮助将不胜感激。
I'm trying to save a tree (extends JTree
) which holds an XML
document to a DOM Object
having changed it's structure.
I have created a new document object, traversed the tree to retrieve the contents successfully (including the original encoding of the XML
document), and now have a ByteArrayInputStream
which has the tree contents (XML
document) with the correct encoding.
The problem is when I parse the ByteArrayInputStream
the encoding is changed to UTF-8
(in the XML
document) automatically.
Is there a way to prevent this and use the correct encoding as provided in the ByteArrayInputStream
.
It's also worth adding that I have already used thetransformer.setOutputProperty(OutputKeys.ENCODING, encoding)
method to retrieve the right encoding.
Any help would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是一个更新的答案,因为 OutputFormat 已被弃用:
第二部分将返回 XML 文档作为字符串
Here's an updated answer since OutputFormat is deprecated :
The second part will return the XML Document as String
经过大量的尝试和错误,我解决了这个问题。
我正在使用
,但将其更改为
,这解决了我的问题。
encoding
是我设置的true
指是否设置缩进。自我注意 - 更仔细地阅读 - 几个小时前我已经看过 javadoc - 如果我能更仔细地阅读就好了。
I solved it, given alot of trial and errors.
I was using
but changed it to
and this solved my problem.
encoding
is what I set it to betrue
refers to whether or not indent is set.Note to self - read more carefully - I had looked at the javadoc hours ago - if only I'd have read more carefully.
这对我有用并且非常简单。不需要变压器或输出格式化程序:
This worked for me and is very simple. No need for a transformer or output formatter: