我现在已经阅读了很多关于如何使用XMLWriter.WriteBase64方法将二进制数据写入XML的帖子(例如this),但我还没有看到过说明如何读取base64编码数据的文章。是否有其他内置方法?我也很难找到关于这个主题的可靠文档。
这是我正在使用的XML文件:
<?xml version="1.0"?>
<pstartdata>
<pdata>some data here</pdata>
emRyWVZMdFlRR0FFQUNoYUwzK2dRUGlBS1ZDTXdIREF ..... and much, much more.
</pstartdata>
创建该文件的C#代码(.Net 4.0):
FileStream fs = new FileStream(Path.GetTempPath() + "file.xml", FileMode.Create);
System.Xml.XmlTextWriter w = new System.Xml.XmlTextWriter(fs, null);
w.Formatting = System.Xml.Formatting.None;
w.WriteStartDocument();
w.WriteStartElement("pstartdata");
#region Main Data
w.WriteElementString("pdata", "some data here");
// Write the binary data
w.WriteBase64(fileData[1], 0, fileData[1].Length);
#endregion (End) Main Data (End)
w.WriteEndDocument();
w.Flush();
fs.Close();
现在,面对真正的挑战……
好的,正如你们所看到的,上面是用 .Net 4.0 写的。不幸的是,XML 文件需要被一个使用 .Net 2.0 的应用程序读取。读取二进制(base 64)数据已经成为了一项相当大的挑战。
用于读取 XML 数据的代码(.Net 2.0):
System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
xDoc.LoadXml(xml_data);
foreach (System.Xml.XmlNode node in xDoc.SelectNodes("pstartdata"))
{
foreach (System.Xml.XmlNode child in node.ChildNodes)
{
MessageBox.Show(child.InnerXml);
}
}
我需要添加什么才能读取上面展示的base64编码数据?
Convert.FromBase64String
方法可以一次性检索未知长度的数据,而不像ReadContentAsBase64
方法那样需要多次调用。 - O. R. Mapper