2017-10-17 144 views
0

我有一個字節數組,文本是xml與「Hei」。我做如何解決代理對(0xD83D,0x27)無效

var bodyText = Encoding.UTF8.GetString(transportMessage.Body); 
var bodyXml = XElement.Parse(bodyText); 

獲取字符串編碼的表情符號&# xD83D;&#x DE0A;所以XElement.Parse拋出:

System.InvalidOperationException:有一個錯誤生成XML文檔。 --- > System.ArgumentException:代理對(0xD83D,0x27)無效。高代理字符(0xD800 - 0xDBFF)必須始終與低代理字符(0xDC00 - 0xDFFF)配對。

我怎樣才能刪除此表情符(或任何其他)我試圖用正則表達式與無效的XML字符[^\x09\x0A\x0D\x20-\xD7FF\xE000-\xFFFD\x10000-x10FFFF]但它不匹配的表情符號。

+0

您是否收到的Unicode?如果是這樣,那麼使用Encoding.Unicode(不是UTF8)。如果你通過html發送XML,那麼你必須編碼和解碼:System.Net.WebUtility.HtmlEncode()和System.Net.WebUtility.HtmlDecode() – jdweng

+0

不,它不是unicode。郵件的其餘部分編碼正確,只是表情符號很奇怪 – Margo

+0

'GetString'不編碼文本,它對它進行解碼。如果'GetString'返回包含'��'的文本,則它必須已經以字節數組的方式編碼。你能顯示字節數組的內容嗎?解碼後的字符串是否真的包含空格('�&#x DE0A;'而不是'��')? – Codo

回答

0

我用這個代碼刪除此:

private static readonly Regex EmojiRegex = new Regex("&#x?[A-Fa-f0-9]+;"); 
private static string ReplaceInvalidXmlCharacterReferences(string input) 
     { 
      if (input.IndexOf("&#") == -1) 
       return input; 

      return EmojiRegex.Replace(input, match => 
      { 
       string ncr = match.Value; 
       uint num; 
       var frmt = NumberFormatInfo.InvariantInfo; 

       bool isParsed = 
        ncr[2] == 'x' ? // the x must be lowercase in XML documents 
        uint.TryParse(ncr.Substring(3, ncr.Length - 4), NumberStyles.AllowHexSpecifier, frmt, out num) : 
        uint.TryParse(ncr.Substring(2, ncr.Length - 3), NumberStyles.Integer, frmt, out num); 

       return isParsed && !XmlConvert.IsXmlChar((char)num) ? "" : ncr; 
      }); 
     }