分类广告


推荐文章

  • 没有找到任何内容!
您当前的位置:中国站长下载网络编程XML专区 → 文章内容

.NET Framework轻松处理XML数据(四)

  • 作者:不详    来源:网络转载    发布时间:2006-6-1 9:16:08
  • 字体大小:
读写流 

有趣的是,reader(阅读器)和writer类提供了基于Base64 和BinHex编码的读写数据流的方法。WriteBase64 和 WriteBinHex方法的功能与其它的写方法的功能存在着细微的差别。它们都是基于流的,这两个方法的功能像一个byte数组而不是一个string。下面的代码首先把一个string转换成一个byte数组,然后把它们写成一个Base64 编码流。Encoding类的GetBytes静态方法完成转换的任务: 

writer.WriteBase64( 

Encoding.Unicode.GetBytes(buf), 

0, buf.Length*2); 
图八中代码演示了把一个string数据转换为Base64 编码的XML流。图九是输出的结果。 


Figure 8 Persisting a String Array as Base64 

using System; 

using System.Text; 

using System.IO; 

using System.Xml; 



class MyBase64Array 



public static void Main(String[] args) 



string outputFileName = "test64.xml"; 

if (args.Length > 0) 

outputFileName = args[0]; // file name 



// 把数组转换成XML 

String[] theArray = {"Rome", "New York", "Sydney", "Stockholm", 

"Paris"}; 



CreateOutput(theArray, outputFileName); 

return; 





private static void CreateOutput(string[] theArray, string filename) 



// 打开XML writer 

XmlTextWriter xmlw = new XmlTextWriter(filename, null); 

//使子元素根据 Indentation 和 IndentChar 设置缩进。此选项只对元素内容进行缩进 

xmlw.Formatting = Formatting.Indented; 

//书写版本为“1.0”的 XML 声明 

xmlw.WriteStartDocument(); 

//写出包含指定文本的注释 。 

xmlw.WriteComment("Array to Base64 XML"); 

//开始写出array节点 

xmlw.WriteStartElement("array"); 

//写出具有指定的前缀、本地名称、命名空间 URI 和值的属性 

xmlw.WriteAttributeString("xmlns", "x", null, "dinoe:msdn-mag"); 

// 循环的写入array的子节点 

foreach(string s in theArray) 



//写出指定的开始标记并将其与给定的命名空间和前缀关联起来 

xmlw.WriteStartElement("x", "element", null); 

//把S转换成byte[]数组, 并把byte[]数组编码为 Base64 并写出结果文本,要写入的字节数为s总长度的2倍,一个string占的字节数是2字节。 

xmlw.WriteBase64(Encoding.Unicode.GetBytes(s), 0, s.Length*2); 

//关闭子节点 

xmlw.WriteEndElement(); 



//关闭根节点,只有两级 

xmlw.WriteEndDocument(); 



// 关闭writer 

xmlw.Close(); 



// 读出写入的内容 

XmlTextReader reader = new XmlTextReader(filname); 

while(reader.Read()) 



//获取节点名为element的节点 

if (reader.LocalName == "element") 





byte[] bytes = new byte[1000]; 

int n = reader.ReadBase64(bytes, 0, 1000); 

string buf = Encoding.Unicode.GetString(bytes); 



Console.WriteLine(buf.Substring(0,n)); 





reader.Close(); 






Figure 9 String Array in Internet Explorer 

Reader类有专门的解释Base64和BinHex编码流的方法。下面的代码片断演示了怎么样用XmlTextReader类的ReadBase64方法解析用Base64和BinHex编码集创建的文档。 

XmlTextReader reader = new XmlTextReader(filename); 

while(reader.Read()) { 

if (reader.LocalName == "element") { 

byte[] bytes = new byte[1000]; 

int n = reader.ReadBase64(bytes, 0, 1000); 

string buf = Encoding.Unicode.GetString(bytes); 

Console.WriteLine(buf.Substring(0,n)); 





reader.Close(); 

从byte型转换成string型是通过Encoding类的GetString方法实现的。尽管我只介绍了基于Base64编码集的代码,但是可以简单的用BinHex替换方法名就可以实现读基于BinHex编码的节点内容(用ReadBinHex方法)。这个技巧也可以用于读任何用byte数据形式表示的二进制数据,尤其是image类型的数据。

上一页  [1] [2]