最近參與的專案需要透過 XML 動態產生表單。看著 UI 設計圖,我面臨一個難題:主表單要用圖示來決定要開啟哪個表單,那麼該如何讓主表單的圖示也能動態載入,並且與要產生的表單相互關聯?我自然又想到了 XML。
查閱 MSDN 後發現,只有 XmlTextWriter.WriteBase64 與 XmlTextReader.ReadBase64 能操作圖片這類二進位位元組資料。但 XmlTextWriter 與 XmlTextReader 遠不如 XmlDocument 來得方便,若用前者就得寫太多程式碼。於是我想起曾看過一篇「如何把圖片資料存進 XML 文件」的文章,翻找許久終於找到相關做法。以下是我的實作程式碼。
在表單載入事件中,先載入 XML 文件,再挑選所有含 Form 的節點,把它們的名稱加入下拉清單:
private XmlDocument document;
private string FilePath = Application.StartupPath + "\\..\\..\\FormStyle.xml";
private void frmMain_Load(object sender, System.EventArgs e)
{
if (document == null)
{
document = new XmlDocument();
document.Load(FilePath);
}
// 只挑選含有 Form 的節點
XmlNodeList FormNodes = document.GetElementsByTagName("Form");
lbIcons.BeginUpdate();
lbIcons.Items.Clear();
foreach (XmlNode node in FormNodes)
{
lbIcons.Items.Add(node.Attributes["Name"].Value);
}
lbIcons.EndUpdate();
}
當使用者切換選項時,查找對應 Form 節點下的 Image 元素,若存在就把元素值轉為 Base64 字串、放進記憶體流,再載入為點陣圖顯示:
private void lbIcons_SelectedValueChanged(object sender, System.EventArgs e)
{
XmlNode node = document.DocumentElement.SelectSingleNode(
string.Format("descendant::Form[@Name='{0}']/Image", lbIcons.SelectedItem.ToString()));
if (node == null)
return;
using (MemoryStream mem = new MemoryStream(Convert.FromBase64String(node.InnerText)))
{
Bitmap bmp = Bitmap.FromStream(mem) as Bitmap;
pictureBox1.Image = bmp;
}
}
新增圖片時,先把點陣圖存進記憶體流,轉成 Base64 字串,再視情況建立 Image 節點並寫回 XML 文件:
private void btnAdd_Click(object sender, System.EventArgs e)
{
if (!File.Exists(txtFilePath.Text) || lbIcons.Items.Count == 0)
return;
if (lbIcons.SelectedIndex == -1)
lbIcons.SelectedIndex = 0;
if (document == null)
{
document = new XmlDocument();
document.Load(FilePath);
}
// 讀入點陣圖並轉為 Base64 字串
string data = null;
Bitmap bmp = new Bitmap(txtFilePath.Text);
using (MemoryStream mem = new MemoryStream())
{
bmp.Save(mem, System.Drawing.Imaging.ImageFormat.Bmp);
data = Convert.ToBase64String(mem.ToArray());
}
// 查找目前選取的 Form 是否已有 Image 節點,若無則新建
XmlNode node = document.DocumentElement.SelectSingleNode(
string.Format("descendant::Form[@Name='{0}']", lbIcons.SelectedItem.ToString()));
XmlNode ImageNode = document.DocumentElement.SelectSingleNode(
string.Format("descendant::Form[@Name='{0}']/Image", lbIcons.SelectedItem.ToString()));
if (ImageNode == null)
{
ImageNode = document.CreateElement("Image");
node.AppendChild(ImageNode);
}
// 將點陣圖資料保存到 XML 文件
ImageNode.InnerText = data;
document.Save(FilePath);
}
透過 Base64 編碼,就能把圖片這類二進位資料安全地存進純文字的 XML 文件中,並隨時還原顯示——這正是動態產生表單時,讓圖示與表單內容保持關聯的關鍵做法。