[英]How to keep character “&” from ISO-8859-1 to UTF-8
我刚刚使用Eclipse编码和ISO-8859-1编写了一个Java文件。 在此文件中,我想创建一个类似的字符串(以便创建XML内容并将其保存到数据库中):
// <image><img src="path_of_picture"></image>
String xmlContent = "<image><img src=\"" + path_of_picture+ "\"></image>";
在另一个文件中,我得到此String并使用此构造函数创建一个新的String:
String myNewString = new String(xmlContent.getBytes(), "UTF-8");
为了被XML解析器理解,我的XML内容必须转换为:
<image><img src="path_of_picture"></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><img src=\"" + content + "\"></image>";
// But the result is just myNewString = <image>&lt;img src="path_of_picture"&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编码写回文件,请执行以下操作:
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.