问题
I've created an AbstractView
in order to output some XML to the browser, as follows:
public abstract class AbstractXmlView extends AbstractView {
public AbstractXmlView() {
setContentType("application/xml");
}
@Override
protected void renderMergedOutputModel(Map<String, Object> model,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
response.setCharacterEncoding("UTF-8");
Document document = new DOMDocument();
document.setXMLEncoding("UTF-8");
buildXmlDocument(model, document, request, response);
response.getOutputStream().print(document.asXML());
}
public abstract void buildXmlDocument(Map<String, Object> model,
Document document, HttpServletRequest request,
HttpServletResponse response) throws Exception;
As you can see, my subclasses would define the buildXMLDocument
method in order to populate the XML Document that would be actually delivered to the browser, so here's a simplified implementation:
public class GetXmlContacts extends AbstractXmlView {
@Override
public void buildXmlDocument(Map<String, Object> model, Document document,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
Element node = document.addElement("node");
node.setText ("I'm unicode áéíóú");
}
Please note the literal string as text in the element node
"I'm unicode áéíóú". When I request this to the server, I obtain an HTTP response with UTF-8 encoding (OK), the XML definition says it's UTF-8, but the node's text would be encoded as ISO-8859-1 (this is my guess, because when I change the encoding with Firefox that string looks OK).
So, why is dom4j enconding a literal string as ISO when it's defined that should be UTF-8? Is there something wrong with my code? Thanks
回答1:
Solved!
Because some bug with dom4j, element.setText()
wouldn't care of the specified encoding and document.asXML()
would return an ISO string, so I modified that line as follows:
response.getOutputStream().write(document.asXML().getBytes("UTF-8"));
And everything worked OK..
来源:https://stackoverflow.com/questions/12606462/incorrect-encoding-in-xml-element-using-dom4j-with-spring-mvc