繁体中文
设为首页
加入收藏
当前位置:程序开发首页 >> XML >> 在.NET Framework中轻松处理XML数据(4-3)

在.NET Framework中轻松处理XML数据(4-3)

2006-11-15 08:00:00  作者:  来源:互联网  浏览次数:0  文字大小:【】【】【
简介:图八中代码演示了把一个string数据转换为Base64 编码的XML流。图九是输出的结果。 Figure 8 Persisting a String Array as Base64 using System; using System.Text; using System.IO; using System.XML; cl...

图八中代码演示了把一个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();

}

}

责任编辑:admin
相关文章