2

I am sending xml to a web service and there I am converting input xml to string and now I am having a problem setting its encoding. Here is a code:

        Element soapinElement = (Element) streams.getSoapin().getValue().getAny();          
        Node node = (Node) soapinElement;
        Document document = node.getOwnerDocument();
        DOMImplementationLS domImplLS = (DOMImplementationLS) document.getImplementation();         
        LSSerializer serializer = domImplLS.createLSSerializer();
        LSOutput output = domImplLS.createLSOutput();
        output.setEncoding("UTF-8");
        Writer stringWriter = new StringWriter();
        output.setCharacterStream(stringWriter);
        serializer.write(document, output);    
        String soapinString = stringWriter.toString();

This code makes a String from request xml. The problem is that when the request XML is encoded not in UTF-8 it produces unreadable characters inside xml elements:

<some element>РћР’Р” Р’РћР</some element>

When I send UTF-8 encoded xml there is no problem. So the question is how to set UTF-8 encoding when converting xml to String.

Default encoding used by JVM is ISO8859-1.

griboedov
  • 876
  • 3
  • 16
  • 33
  • I am confused. Did you solve the problem? – A.sharif Jun 24 '15 at 14:51
  • Are you asking a question or are you just telling us that you have solved it by setting the encoding to UTF-8? The default character encoding is not always ISO-8859-1; what the default is depends on your system. – Jesper Jun 24 '15 at 14:54

2 Answers2

1

The setEncoding method says what the encoding actually is, not what you want it to be. The XML library won't convert the characters.

See this question: Meaning of XML encoding

If you want to convert the encoding, that is another question.

Community
  • 1
  • 1
rghome
  • 8,529
  • 8
  • 43
  • 62
0

I would rethink my whole approach if I were you, generally XML should be kept as a tree.

But if you really need a string, try this

    final StringWriter sw = new StringWriter();
    try {
        TransformerFactory.newInstance().newTransformer().transform(
                new DOMSource(document),
                new StreamResult(sw)
        );
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    }

    // Now you have the XML as a String:
    System.out.println(sw.toString());
artbristol
  • 32,010
  • 5
  • 70
  • 103