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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10582968/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 01:40:22  来源:igfitidea点击:

How to set UTF-16 encoding format for Xml?

javaxmlxml-serializationxsd

提问by vinothp

I am in need to create xml as a string to pass to server. I have managed to convert the data into xml but the encoding format set to utf-8 as default. What i need is i want to set it as utf-16 format. But i haven't got any idea of setting it.

我需要创建 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);
  }
}

Thanks guys

多谢你们

采纳答案by michael667

Thisarticle might help you. Basically, you call setOutputPropertywith OutputKeys.ENCODINGas key and the desired encoding ("UTF-16") as value.

这篇文章或许能帮到你。基本上,您setOutputProperty使用OutputKeys.ENCODING作为键和所需的编码(“UTF-16”)作为值进行调用。

回答by sp00m

I haven't tested, but that should do the trick:

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

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