DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> XML學習教程 >> XML詳解
在 .NET Framework 中輕鬆處理 XML(四):Base64 編碼
編輯:XML詳解     

下面的程式示範如何把一個字串陣列轉換為 Base64 編碼的 XML 流。

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];

// 把陣列轉換成 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;
// 寫出 XML 宣告
XMLw.WriteStartDocument();
XMLw.WriteComment("Array to Base64 XML");
// 開始寫出 array 節點
XMLw.WriteStartElement("array");
XMLw.WriteAttributeString("XMLns", "x", null, "dinoe:msdn-mag");

foreach(string s in theArray)
{
XMLw.WriteStartElement("x", "element", null);
// 把 s 轉成 byte[] 並以 Base64 編碼寫出
XMLw.WriteBase64(Encoding.Unicode.GetBytes(s), 0, s.Length*2);
XMLw.WriteEndElement();
}
XMLw.WriteEndDocument();
XMLw.Close();

// 讀出寫入的內容
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();
}
}

這段程式先用 XMLTextWriter 建立 XML 文檔,透過 WriteBase64 把每個字串以 Base64 編碼寫入節點,之後再用 XMLTextReader 搭配 ReadBase64 讀回並還原內容,示範了 .NET 中二進位數據與 XML 之間的雙向轉換。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved