将TreeView中导出为XML数据
//使用范例:
TreeViewToXmlB m_TreeViewToXmlB = new TreeViewToXmlB();
m_TreeViewToXmlB.exportToXml(this.TreeView1,Server.MapPath(@".\xml.xml"));
====================================================
using System;
using Microsoft.Web.UI.WebControls;
using System.Collections;
using System.IO;
//using System.Windows.Forms;
namespace treeview_DB
{
/// <summary>
/// 将TreeView中导出为XML数据
/// </summary>
public class TreeViewToXmlB
{
//XML每行的内容
private string xmlLine = "";
//用于写XML文件
private StreamWriter sr;
//// <summary>
/// 构造函数
/// </summary>
public TreeViewToXmlB()
{
}
/// <summary>
/// 将TreeView中导出为XML数据
/// </summary>
/// <param name="tv">TreeView控件</param>
/// <param name="filename">XML文件的保存路径</param>
public void exportToXml(TreeView tv, string filename)
{
sr = new StreamWriter(filename, false, System.Text.Encoding.UTF8);
//写文件头部内容
//下面是生成RSS的OPML文件
sr.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
sr.WriteLine("<opml version=\"1.0\">");
sr.WriteLine("<head>");
sr.WriteLine("<title>RSS</title>");
sr.WriteLine("</head>");
sr.WriteLine("<body>");
//遍历根节点
foreach (TreeNode node in tv.Nodes)
{
if (node.Nodes.Count == 0)
{
xmlLine = GetRSSText(node);
}
else
{
xmlLine = GetDirectoryText(node);
}
sr.WriteLine(xmlLine);
//递归遍历节点
parseNode(node);
}
//写文件尾部内容
sr.WriteLine("</body>");
sr.WriteLine("</opml>");
sr.Close();
}
//递归遍历节点内容,最关键的函数
private void parseNode(TreeNode tn)
{
IEnumerator ie = tn.Nodes.GetEnumerator();
while (ie.MoveNext())
{
TreeNode ctn = (TreeNode) ie.Current;
//为最底层节点,即该节点为RSS节点
if (ctn.Nodes.Count == 0)
{
xmlLine = GetRSSText(ctn);
sr.WriteLine(xmlLine);
}
else//不是最底层节点,即该节点为目录节点
{
xmlLine = GetDirectoryText(ctn);
sr.WriteLine(xmlLine);
}
//如果还有子节点则继续遍历
if (ctn.Nodes.Count > 0)
{
parseNode(ctn);
}
}
sr.WriteLine("</outline>");
}
//成生RSS节点的XML文本行
private string GetRSSText(TreeNode node)
{
//根据Node属性生成XML文本
string rssText = "<outline type=\"rss\" text=\"" + node.Text + "\" xmlUrl=\"URL\"/>";
return rssText;
}
//成生目录节点的XML文本行
private string GetDirectoryText(TreeNode node)
{
//根据Node属性生成XML文本
string directoryText = "<outline text=\"" + node.Text + "\">";
return directoryText;
}
}
}