2

我创建了一个类并将其转换为 xml。

问题是,当我将类 xml 字符串转换为字节
时,ASCII.GetBytes返回一个字节数组,
ascArray

它总是一个?字符,所以 xml 像这样开始

?<?xml version="1.0" encoding="utf-8"?>

为什么会这样?

这是代码:

  WorkItem p = new WorkItem();

  // Fill the class with whatever need to be sent to client
  OneItem posts1 = new OneItem();
  posts1.id = "id 1";
  posts1.username = "hasse";
  posts1.message = "hej again";
  posts1.time = "time1";
  p.setPost(posts1);

  OneItem posts2 = new OneItem();
  posts2.id = "id 2";
  posts2.username = "bella";
  posts2.message = "hej again again";
  posts2.time = "time2";
  p.setPost(posts2);

  // convert the class WorkItem to xml
  MemoryStream memoryStream = new MemoryStream();
  XmlSerializer xs = new XmlSerializer(typeof(WorkItem));
  XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
  xs.Serialize(xmlTextWriter, p);

  // send the xml version of WorkItem to client
  byte[] data = memoryStream.ToArray();
  clientStream.Write(data, 0, data.Length);
  Console.WriteLine(" send.." + data);
  clientStream.Close();
4

1 回答 1

4

我强烈怀疑数据以字节顺序标记开头,不能用 ASCII 表示。

不清楚你为什么要做你正在做的事情,尤其是在MemoryStream. 为什么要创建一个 UTF-8 编码的字节数组,然后将其解码为字符串(我们不知道是什么UTF8ByteArrayToString),然后将其转换字节数组?为什么不直接将字节数组写入客户端呢?如果您需要将数据作为字符串,我会使用一个子类StringWriter来宣传它使用 UTF-8 作为编码。如果您不需要它作为字符串,只需坚持字节数组即可。

请注意,即使除了第一个字符之外,您已经获得了以 UTF-8 编码的 XML 文档这一事实意味着字符串中很可能还有其他非 ASCII 字符。你为什么在这里使用ASCII?

编辑:为了清楚起见,您从根本上应用了有损转换,并且不必要地进行了操作。即使你想要数据的本地副本,你也应该有这样的东西:

// Removed bad try/catch block - don't just catch Exception, and don't
// just swallow exceptions
MemoryStream memoryStream = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(WorkItem));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, p);

// Removed pointless conversion to/from string
// Removed pointless BinaryWriter (just use the stream)

// An alternative would be memoryStream.WriteTo(clientStream);
byte[] data = memoryStream.ToArray();
clientStream.Write(data, 0, data.Length);
Console.WriteLine(" send.." + data);

// Removed Close calls - you should use "using" statements to dispose of
// streams automatically.
于 2012-06-14T05:47:15.770 回答