問題描述
我正在嘗試將保存 XML
文檔的樹(擴展 JTree
)保存為已更改其結構的 DOM 對象
.
I'm trying to save a tree (extends JTree
) which holds an XML
document to a DOM Object
having changed it's structure.
我創建了一個新的文檔對象,遍歷樹成功檢索了內容(包括XML
文檔的原始編碼),現在有了一個ByteArrayInputStream
具有正確編碼的樹內容(XML
文檔).
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.
問題是當我解析 ByteArrayInputStream
時,編碼會自動更改為 UTF-8
(在 XML
文檔中).
The problem is when I parse the ByteArrayInputStream
the encoding is changed to UTF-8
(in the XML
document) automatically.
有沒有辦法防止這種情況并使用 ByteArrayInputStream
中提供的正確編碼.
Is there a way to prevent this and use the correct encoding as provided in the ByteArrayInputStream
.
值得補充的是,我已經使用了transformer.setOutputProperty(OutputKeys.ENCODING, encoding)
方法來檢索正確的編碼.
It's also worth adding that I have already used the
transformer.setOutputProperty(OutputKeys.ENCODING, encoding)
method to retrieve the right encoding.
任何幫助將不勝感激.
推薦答案
這是一個更新的答案,因為 OutputFormat 已被棄用:
Here's an updated answer since OutputFormat is deprecated :
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(document), new StreamResult(writer));
String output = writer.getBuffer().toString().replaceAll("
|
", "");
第二部分將 XML 文檔作為字符串返回
The second part will return the XML Document as String
這篇關于Java、XML DocumentBuilder - 解析時設置編碼的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!