How to set UTF-16 encoding format for Xml?

10,305

Solution 1

This article might help you. Basically, you call setOutputProperty with OutputKeys.ENCODING as key and the desired encoding ("UTF-16") as value.

Solution 2

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

transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-16");
Share:
10,305
vinothp
Author by

vinothp

Do what you like. Believe in what you do. Young and energetic individual with great passion on Mobile Application Development. Currently working as a full time mobile application developer for Android and iOS. In free time working on personal projects as well. My First Personal App - Location Plotter/ House Viewing

Updated on June 04, 2022

Comments

  • vinothp
    vinothp almost 2 years

    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.

      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