首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将DOM元素编码从CP1251转换为UTF8

将DOM元素编码从CP1251转换为UTF8
EN

Stack Overflow用户
提问于 2015-06-25 23:52:33
回答 1查看 1.1K关注 0票数 2

我有一个简单的服务器端代码,它接受请求xml并将其作为字符串插入到Oracle数据库的Clob列中。问题是客户端发送的请求xml使用CP1251编码的文本,但我需要将其插入到使用UTF8编码的Oracle中。现在我为CP1251使用的代码是:

代码语言:javascript
复制
        Element soapinElement = (Element) streams.getSoapin().getValue().getAny();  //retrieve request xml      
        Node node = (Node) soapinElement;
        Document document = node.getOwnerDocument();
        DOMImplementationLS domImplLS = (DOMImplementationLS) document.getImplementation();         
        LSSerializer serializer = domImplLS.createLSSerializer();
        LSOutput output = domImplLS.createLSOutput();
        output.setEncoding("CP1251");
        Writer stringWriter = new StringWriter();
        output.setCharacterStream(stringWriter);
        serializer.write(document, output);
        String soapinString = stringWriter.toString();

此代码可识别以CP1251编码的文本。任务是使用UTF-8编码的可读文本来制作相同的文本。请提出任何建议。

我试过了,但它产生了不可读的字符,而不是西里尔字母:

代码语言:javascript
复制
        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("CP1251");
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        output.setByteStream(byteArrayOutputStream);
        serializer.write(document, output);
        byte[] result = byteArrayOutputStream.toByteArray();
        InputStream is = new ByteArrayInputStream(result);
        Reader reader = new InputStreamReader(is, "CP1251");
        OutputStream out = new ByteArrayOutputStream();
        Writer writer = new OutputStreamWriter(out, "UTF-8");
        char[] buffer = new char[10];
        int read;
        while ((read = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, read);
        }           
        reader.close();
        writer.close();
        String soapinString = out.toString();
EN

回答 1

Stack Overflow用户

发布于 2015-06-26 00:39:11

您可以解码CP1251字符集数据,如下所示

代码语言:javascript
复制
Charset utf8charset = Charset.forName("UTF-8");
Charset cp1251charset = Charset.forName("CP1251");

// decode CP1251
        CharBuffer data = cp1251charset.decode(ByteBuffer.wrap(result));

并编码为UTF-8字符集

代码语言:javascript
复制
// encode UTF-8
        ByteBuffer outputBuffer = utf8charset.encode(data);

并将ByteBuffer转换为byte[]

代码语言:javascript
复制
// UTF-8 Value        
        byte[] outputData = outputBuffer.array();

这可能会解决你的问题。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31055126

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档