2016-04-27 15 views
0

您會得到一個字符串,其中包含任何種類的字符(UTF-8),包括特殊字符(如表情符號/表情符號)。 您必須生成一個包含接收到的字符串的XML元素並將其傳遞給XSLT轉換器引擎。安全地準備一個字符串和Java表情符號圖標用於XML和XSLT轉換

當我得到轉換錯誤時,我想知道Java代碼在將其插入最終XML之前如何處理該字符串,以便XSLT轉換不會失敗。

我目前在Java是這樣的:

String inputValue = ...; // you get this string by an external client 
Element target = ...; // element of an XML where you have to add the string 
String xml10pattern = "[^" 
        + "\u0009\r\n" 
        + "\u0020-\uD7FF" 
        + "\uE000-\uFFFD" 
        + "\ud800\udc00-\udbff\udfff" 
        + "]"; // this removes the illegal characters in XML 
inputValue = inputValue.replaceAll(xml10pattern, ""); 
target.setAttribute("text", inputValue); 

但儘管如此,一些是爲了使其更加安全不見了?

回答

1

阿帕奇公共圖書館有StringEscapeUTils.escapeXML(string)。這允許您的屬性中有&

+1

不,它只刪除非法的XML字符,請參閱「NOT」(^)在beginng ...我從http://stackoverflow.com/questions/4237625/removing-invalid-xml-characters-from -a-string-in-java/4237934#4237934 – basZero

+1

刪除了錯誤的部分。 –

0

一個廉價的可能性是剝離所有非ASCII字符,以便你只是傳遞一個乾淨的文本字符串,它(但換行等):

String inputValue = ...; // you get this string by an external client 
Element target = ...; // element of an XML where you have to add the string 
String xml10pattern = "[^" 
        + "\u0009\r\n" 
        + "\u0020-\uD7FF" 
        + "\uE000-\uFFFD" 
        + "\ud800\udc00-\udbff\udfff" 
        + "]"; // this removes the illegal characters in XML 
inputValue = inputValue.replaceAll(xml10pattern, ""); 
inputValue = inputValue.replaceAll("[^\\x00-\\xFF]", ""); 
target.setAttribute("text", inputValue); 

對這個有什麼想法?

相關問題