簡體   English   中英

用Java生產UTF-8編碼的XML

[英]Producing UTF-8 encoded XML in Java

這是我正在使用的代碼

try {
String str = "\uC3BC and \uC3B6 and <&> für";

DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.newDocument();
Element root = doc.createElement("test");
root.setAttribute("attribute", str);
doc.appendChild(root);

DOMSource domSource = new DOMSource(doc);
// FileOutputStream out = new FileOutputStream("test.xml");
Writer out = new OutputStreamWriter(new FileOutputStream("test.xml"), "UTF8");

Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.transform(domSource, new StreamResult(out));

out.close();
} catch (Exception e) {
e.printStackTrace();
}

輸出是

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<test attribute="쎼 and 쎶 and &lt;&amp;&gt; für"/>

我希望它輸出

attribute="&#xc3bc and &#xc3b6 ..."

我該如何實現?

我正在使用Java 1.6-20

這類似於使用Java和UTF-8編碼生成有效的XML

如果您不希望將XML編碼為UTF-8,則不應該告訴轉換器這樣做。

如果我正確理解您的問題

transformer.setOutputProperty(OutputKeys.ENCODING, "US-ASCII");

應該產生您想要的輸出

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM