上周我遇到了这个问题。我必须序列化一个PDF文件,然后将它在XML文件中发送到服务器。
如果使用的是.NET,则可以将二进制文件直接转换为base64字符串,并将其粘贴在XML元素中。
string base64 = Convert.ToBase64String(File.ReadAllBytes(fileName));
或者,在XmlWriter对象中内置了一个方法。在我的特殊情况下,我必须包括Microsoft的数据类型名称空间:
StringBuilder sb = new StringBuilder();
System.Xml.XmlWriter xw = XmlWriter.Create(sb);
xw.WriteStartElement("doc");
xw.WriteStartElement("serialized_binary");
xw.WriteAttributeString("types", "dt", "urn:schemas-microsoft-com:datatypes", "bin.base64");
byte[] b = File.ReadAllBytes(fileName);
xw.WriteBase64(b, 0, b.Length);
xw.WriteEndElement();
xw.WriteEndElement();
string abc = sb.ToString();
字符串abc看起来像这样:
JVBERi0xLjMKJaqrrK0KNCAwIG9iago8PCAvVHlwZSAvSW5mbw...(plus lots more)