1

我通过 WebClient 将签名的 XML 发送到网关。现在我必须确保节点值只包含德语字母。我有 2 个测试词。第一个通过使用得到很好的转换:

string foreignString = "Łůj꣥ü";
Encoding utf8 = Encoding.UTF8;
Encoding iso = Encoding.GetEncoding("ISO-8859-1");
byte[] utfBytes = Encoding.Convert(iso, utf8, iso.GetBytes(foreignString));
string result = utf8.GetString(utfBytes);

但在第二个字符串中是一个字符,它也包含在 UTF-8 编码中。它的

ç (Latin small letter c with cedilla)

在用其他编码进行了一些测试后,我总是得到相同的结果:字符总是在那里。有什么意义,因为它是 UTF-8 表的一部分 :)

所以我的问题是:有没有办法在不删除德语变音符号的情况下掩盖所有法语、葡萄牙语和西班牙语字符?

提前致谢!

4

1 回答 1

2

Encoding您可以使用附加的特殊规则基于 ISO-8859-1 编码创建自己的类:

class GermanEncoding : Encoding {

  static readonly Encoding iso88791Encoding = Encoding.GetEncoding("ISO-8859-1");

  static readonly Dictionary<Char, Char> charMappingTable = new Dictionary<Char, Char> {
    { 'À', 'A' },
    { 'Á', 'A' },
    { 'Â', 'A' },
    { 'ç', 'c' },
    // Add more mappings
  };

  static readonly Dictionary<Byte, Byte> byteMappingTable = charMappingTable
    .ToDictionary(kvp => MapCharToByte(kvp.Key), kvp => MapCharToByte(kvp.Value));

  public override Int32 GetByteCount(Char[] chars, Int32 index, Int32 count) {
    return iso88791Encoding.GetByteCount(chars, index, count);
  }

  public override Int32 GetBytes(Char[] chars, Int32 charIndex, Int32 charCount, Byte[] bytes, Int32 byteIndex) {
    var count = iso88791Encoding.GetBytes(chars, charIndex, charCount, bytes, byteIndex);
    for (var i = byteIndex; i < byteIndex + count; ++i)
      if (byteMappingTable.ContainsKey(bytes[i]))
        bytes[i] = byteMappingTable[bytes[i]];
    return count;
  }

  public override Int32 GetCharCount(Byte[] bytes, Int32 index, Int32 count) {
    return iso88791Encoding.GetCharCount(bytes, index, count);
  }

  public override Int32 GetChars(Byte[] bytes, Int32 byteIndex, Int32 byteCount, Char[] chars, Int32 charIndex) {
    return iso88791Encoding.GetChars(bytes, byteIndex, byteCount, chars, charIndex);
  }

  public override Int32 GetMaxByteCount(Int32 charCount) {
    return iso88791Encoding.GetMaxByteCount(charCount);
  }

  public override Int32 GetMaxCharCount(Int32 byteCount) {
    return iso88791Encoding.GetMaxCharCount(byteCount);
  }

  static Byte MapCharToByte(Char c) {
    // NOTE: Assumes that each character encodes as a single byte.
    return iso88791Encoding.GetBytes(new[] { c })[0];
  }

}

此编码基于您希望使用 ISO-8859-1 编码以及一些附加限制的事实,您希望将“非德语”字符映射到其 ASCII 等效字符。内置的 ISO-8859-1 编码知道如何映射ŁL,因为 ISO-8859-1 是单字节字符集,您可以对字节进行额外的映射,因为每个字节对应一个字符。这是在GetBytes方法中完成的。

您可以使用以下代码“清理”字符串:

var encoding = new GermanEncoding();
string foreignString = "Łůj꣥üç";
var bytes = encoding.GetBytes(foreignString);
var result = encoding.GetString(bytes);

结果字符串是LujeLAüc.

请注意,该实现非常简单,它使用字典来执行字节的附加映射步骤。这可能效率不高,但在这种情况下,您可以考虑使用 256 字节映射数组等替代方法。此外,您需要扩展charMappingTable以包含您要执行的所有其他映射。

于 2012-10-26T07:36:05.540 回答