2013-07-18 14 views
0

我剛剛使用ISO-8859-1的Eclipse編碼編寫了一個java文件。 在這個文件中,我想創建一個字符串這樣那樣的(爲了創建一個XML的內容並把它保存到數據庫中):如何將字符「&」從ISO-8859-1保留爲UTF-8

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

在另一個文件中,我得到這個字符串,並創建一個新的String與此構造函數:

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

爲了通過XML解析器可以理解,我的XML內容必須轉換爲:

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

不幸的是,我無法找到如何令狀e 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> 

你有什麼想法嗎?

+0

你正在使用哪個xml解析器?我不認爲字符串中任何形式的'<' or '>'符號都會被任何一個解析器解析。 – rahulserver

+0

這與文本編碼有什麼關係? &字符是ASCII,所以UTF-8和iso-8859-1的編碼方式相同,不存在混淆的可能性。 – Joni

+1

你的問題更可能與字符轉義有關,而不是編碼。你知道[CDATA](http://stackoverflow.com/questions/2784183/what-does-cdata-in-xml-mean)嗎? – reto

回答

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

我不覺得你的問題是有關的編碼,但如果你想「創建一個String,如這樣的(爲了創建一個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); 
    } 

參考this SO回答。

+0

這不完全是我的目標,但我已經使用CDATA,它的工作原理。 –

相關問題