XML——>treeciew
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Xml;
namespace TreeExXML
{
class TreeExXMLCls
{
private TreeView thetreeview;
private string xmlfilepath;
XmlDocument textdoc;
public TreeExXMLCls()
{
//----构造函数
textdoc = new XmlDocument();
}
~TreeExXMLCls()
{
//----析构函数
}
#region 遍历XML并实现向tree的转化
/// <summary>
/// 遍历treeview并实现向XML的转化
/// </summary>
/// <param name="XMLFilePath">XML输出路径</param>
/// <param name="TheTreeView">树控件对象</param>
/// <returns>0表示函数顺利执行</returns>
public int XMLToTree(string XMLFilePath, TreeView TheTreeView)
{
//-------重新初始化转换环境变量
thetreeview = TheTreeView;
xmlfilepath = XMLFilePath;
//-------重新对XMLDocument对象赋值
textdoc.Load(xmlfilepath);
XmlNode root = textdoc.SelectSingleNode("Sinumerik");
TreeNode bootTreeNode = new TreeNode();
bootTreeNode.Text = "Sinumerik";
thetreeview.Nodes.Add(bootTreeNode);
foreach (XmlNode subXmlnod in root.ChildNodes)
{
//TreeNode trerotnod = new TreeNode();
TreeNode treeNode = new TreeNode();
XmlElement element = (XmlElement)subXmlnod;
treeNode.Text = element .GetAttribute ("Title");
treeNode.ToolTipText = element.GetAttribute("Description");
bootTreeNode.Nodes.Add(treeNode );
//xml三层结构---从外到内
TransXML(subXmlnod.ChildNodes, treeNode);
}
return 0;
}
private int TransXML(XmlNodeList Xmlnodes, TreeNode partrenod)
{
//------遍历XML中的所有节点,仿照treeview节点遍历函数
foreach (XmlNode xmlnod in Xmlnodes)
{
TreeNode subtreeNode = new TreeNode();
XmlElement element = (XmlElement)xmlnod ;
subtreeNode.Text = element.GetAttribute("Title");
subtreeNode.ToolTipText = element.GetAttribute("Description");
subtreeNode.Tag = element.GetAttribute("nodeClass");
partrenod.Nodes.Add(subtreeNode);
if (xmlnod.ChildNodes.Count > 0)
{
TransXML(xmlnod.ChildNodes, subtreeNode);
}
}
return 0;
}
#endregion
}
}