简体   繁体   中英

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

I'd just written a java file using Eclipse encoding with ISO-8859-1. In this file, I want to create a String such like that (in order to create a XML content and save it into a database) :

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

In another file, I get this String and create a new String with this constructor :

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

In order to be understood by a XML parser, my XML content must be converted to :

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

Unfortunately, I can't find how to write xmlContent to get this result in myNewString. I tried two methods :

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

Do you have any idea ?

This is unclear. But Strings don't have an encoding. So when you write

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

you will get various results depending on your default encoding setting (which is used for the getBytes() method).

If you want to read a file encoded with ISO-8859-1, you simply do:

  • read the bytes from the file: byte[] bytes = Files.readAllBytes(path);
  • create a string using the file's encoding: String content = new String(bytes, "ISO-8859-1);

If you need to write back the file with a UTF-8 encoding you do:

  • convert the string to bytes with UTF-8 encoding: byte[] utfBytes = content.getBytes("UTF-8");
  • write the bytes to the file: Files.write(path, utfBytes);

I dont feel that your question is related to encoding but if you want to "create a String such like that (in order to create a XML content and save it into a database)", you can use this code:

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);
    }

Refer this SO answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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