2011-09-30 35 views
1

XML這是我使用生產UTF-8編碼在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

這類似於Producing valid XML with Java and UTF-8 encoding

+1

請告訴我問題的輸出? –

+0

**爲什麼**你想要字符引用而不是字符本身?由於您使用的是UTF-8,因此您無需(並且無論如何都攜帶完全相同的信息)。 –

+0

我的道歉,我沒有清楚說明我的問題。我想逃避。 – bouncyrabbit

回答

6

如果您不想在XML編碼爲UTF-8,你不應該告訴變壓器這樣做。

如果我明白你的問題正確

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

應該產生要