0

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

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

在另一个文件中,我得到这个字符串并使用这个构造函数创建一个新的字符串:

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

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

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

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

       // 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>

你有什么主意吗 ?

4

2 回答 2

0

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

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);
于 2013-07-18T08:34:30.647 回答
0

我不认为您的问题与编码有关,但如果您想“创建这样的字符串(以便创建 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 答案。

于 2013-07-18T08:44:53.930 回答