繁体   English   中英

如何保持字符“&”从ISO-8859-1到UTF-8

[英]How to keep character “&” from ISO-8859-1 to UTF-8

我刚刚使用Eclipse编码和ISO-8859-1编写了一个Java文件。 在此文件中,我想创建一个类似的字符串(以便创建XML内容并将其保存到数据库中):

//   <image>&lt;img src="path_of_picture"&gt;</image>
String xmlContent = "<image><img src=\"" + path_of_picture+ "\"></image>"; 

在另一个文件中,我得到此String并使用此构造函数创建一个新的String:

String myNewString = new String(xmlContent.getBytes(), "UTF-8");

为了被XML解析器理解,我的XML内容必须转换为:

<image>&lt;img src="path_of_picture"&gt;</image>

不幸的是,我找不到如何在myNewString中编写xmlContent来获得此结果的方法。 我尝试了两种方法:

       // First : 
String xmlContent = "<image><img src=\"" + content + "\"></image>"; 
// But the result is just myNewString = <image><img src="path_of_picture"></image>
// and my XML parser can't get the content of <image/>

    //Second :
String xmlContent = "<image>&lt;img src=\"" + content + "\"&gt;</image>";
// But the result is just myNewString = <image>&amp;lt;img src="path_of_picture"&amp;gt;</image>

你有什么主意吗 ?

这还不清楚。 但是字符串没有编码。 所以当你写

String s = new String(someOtherString.getBytes(), someEncoding);

根据默认的编码设置(用于getBytes()方法),您将获得各种结果。

如果要读取使用ISO-8859-1编码的文件,只需执行以下操作:

  • 从文件中读取字节: byte[] bytes = Files.readAllBytes(path);
  • 使用文件的编码创建一个字符串: String content = new String(bytes, "ISO-8859-1);

如果您需要使用UTF-8编码写回文件,请执行以下操作:

  • 使用UTF-8编码将字符串转换为字节: byte[] utfBytes = content.getBytes("UTF-8");
  • 将字节写入文件: Files.write(path, utfBytes);

我不认为您的问题与编码有关,但是如果您想“创建这样的字符串(以便创建XML内容并将其保存到数据库中)”,则可以使用以下代码:

public static Document loadXMLFromString(String xml) throws Exception
    {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(xml));
        return builder.parse(is);
    }

请参阅 SO答案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM