gpt4 book ai didi

java - Xml如何设置UTF-16编码格式?

转载 作者:数据小太阳 更新时间:2023-10-29 02:05:22 25 4
gpt4 key购买 nike

我需要将 xml 创建为要传递给服务器的字符串。我已经设法将数据转换为 xml,但编码格式默认设置为 utf-8。我需要的是我想将它设置为 utf-16 格式。但我还没有设置它的任何想法。

  private void XmlCreation(int size,List<DataItem> item) throws ParserConfigurationException, TransformerException
{
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.newDocument();
Element rootElement = document.createElement("ArrayOfDataItem");
document.appendChild(rootElement);
for (DataItem in: item)
{
Element subroot = document.createElement("DataItem");
rootElement.appendChild(subroot);
Element em = document.createElement(in.getKey());
em.appendChild(document.createTextNode(in.getValue()));
subroot.appendChild(em);
}

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
java.io.StringWriter sw = new java.io.StringWriter();
DOMSource source = new DOMSource(document);

StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);

String xml = sw.toString();
System.out.println(xml);
}
}

谢谢大家

最佳答案

我还没有测试过,但这应该可以解决问题:

transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-16");

关于java - Xml如何设置UTF-16编码格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10582968/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com