XML在数据交换中的作用越来越大。在公文无纸化传输中,传输的不仅有文本,还有签名、word文件、其他附件等等,如何将这些二进制文件嵌入XML中进行传输,这里以嵌入一个签名图片为例,做简单介绍。 转
1.将二进制文件以Base64格式写入XML
public void InsertFileToXml()
{
FileStream fs
=
File.OpenRead(
"d:\\sign.gif");
byte
[] buffer
=
new byte[fs.Length];
![InBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
fs.Read(buffer, 0, buffer.Length);
![InBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
XmlTextWriter writer
=
new
XmlTextWriter(
"d:\\user.xml",System.Text.Encoding.Default);
![InBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
writer.Formatting = Formatting.Indented;
![InBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
writer.WriteStartDocument();
![InBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
writer.WriteStartElement(
"User");
![InBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
writer.WriteElementString(
"
First_Name
"
,
"John");
![InBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
writer.WriteElementString(
"
Last_Name
"
,
"Wang");
![InBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
writer.WriteStartElement(
"Signature");
![InBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
writer.WriteAttributeString(
"
filename
"
,
"sign.gif");
![InBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
writer.WriteBase64(buffer,0,buffer.Length);
![InBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
writer.WriteEndElement();
![InBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
writer.WriteEndElement();
![InBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
writer.WriteEndDocument();
![InBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
writer.Flush();
![InBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
writer.Close();
![ExpandedBlockEnd.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockEnd.gif)
}
生成后的XML(user.xml)内容如下:
<?xml version="1.0" encoding="gb2312"?>
![None.gif](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
<User>
![None.gif](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
<
First_Name
>
John
</First_Name>
![None.gif](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
<
Last_Name
>
Wang
</Last_Name>
![None.gif](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
<
Signature
filename
="sign.gif"
>
R0lGODlhZAAZAIAAAJ0IDf///yH5BAAAAAAALAAAAABkABkAAAKXjI+py+0Po5y02ouz3rz7D4biSJbmiabqAbQr2sbANL+Ja9WNzDv6qvvlJMKdLVD74WjESJH1HLKQhuSSEoU2FzHGEqdEBmfW5CV7FaepXe3za4YKs1Tp7a2V16t8hZV9h5WhhJZXFSfWdzfGQffQ49OGEDSleOIIQ+mngnk5eWQIKsrVOcpJZpqqWKpKotkq+gp7JKtQAAA7
</Signature>
![None.gif](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
</
User
>
2.从XML中读取文件