C# XMLTree

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Windows.Forms;

namespace WindowsFormsApplication7
{

        class TreeExXMLCls
        {
            private TreeView thetreeview;
            private string xmlfilepath;
            XmlTextWriter textWriter;
            XmlNode Xmlroot;
            XmlDocument textdoc;

            public TreeExXMLCls()
            {
                //----构造函数  
                textdoc = new XmlDocument();

            }

            ~TreeExXMLCls()
            {
                //----析构函数  
            }

            #region 遍历treeview并实现向XML的转化
            /// <summary>     
            /// 遍历treeview并实现向XML的转化  
            /// </summary>     
            /// <param name="TheTreeView">树控件对象</param>     
            /// <param name="XMLFilePath">XML输出路径</param>     
            /// <returns>0表示函数顺利执行</returns>     

            public int TreeToXML(TreeView TheTreeView, string XMLFilePath)
            {
                //-------初始化转换环境变量  
                thetreeview = TheTreeView;
                xmlfilepath = XMLFilePath;
                textWriter = new XmlTextWriter(xmlfilepath, null);

                //-------创建XML写操作对象  
                textWriter.Formatting = Formatting.Indented;

                //-------开始写过程,调用WriteStartDocument方法  
                textWriter.WriteStartDocument();

                //-------写入说明  
                textWriter.WriteComment("this XML is created from a tree");

                //-------添加第一个根节点  
                textWriter.WriteStartElement("TreeExXMLCls");
                textWriter.WriteEndElement();

                //------ 写文档结束,调用WriteEndDocument方法  
                textWriter.WriteEndDocument();

                //-----关闭输入流  
                textWriter.Close();

                //-------创建XMLDocument对象  
                textdoc.Load(xmlfilepath);

                //------选中根节点  
                XmlElement Xmlnode = textdoc.CreateElement(thetreeview.Nodes[0].Text);
                Xmlroot = textdoc.SelectSingleNode("TreeExXMLCls");

                //------遍历原treeview控件,并生成相应的XML  
                TransTreeSav(thetreeview.Nodes, (XmlElement)Xmlroot);
                return 0;
            }

            private int TransTreeSav(TreeNodeCollection nodes, XmlElement ParXmlnode)
            {

                //-------遍历树的各个故障节点,同时添加节点至XML  
                XmlElement xmlnode;
                Xmlroot = textdoc.SelectSingleNode("TreeExXMLCls");

                foreach (TreeNode node in nodes)
                {
                    xmlnode = textdoc.CreateElement(node.Text);
                    ParXmlnode.AppendChild(xmlnode);

                    if (node.Nodes.Count > 0)
                    {
                        TransTreeSav(node.Nodes, xmlnode);
                    }
                }
                textdoc.Save(xmlfilepath);
                return 0;
            }

            #endregion

            #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("Targ");//读的xml的节点名

                foreach (XmlNode subXmlnod in root.ChildNodes)
                {
                    TreeNode trerotnod = new TreeNode();
                    trerotnod.Text = subXmlnod.Name;
                    thetreeview.Nodes.Add(trerotnod);
                    TransXML(subXmlnod.ChildNodes, trerotnod);

                }
                return 0;
            }

            private int TransXML(XmlNodeList Xmlnodes, TreeNode partrenod)
            {
                //------遍历XML中的所有节点,仿照treeview节点遍历函数  
                foreach (XmlNode xmlnod in Xmlnodes)
                {
                    TreeNode subtrnod = new TreeNode();
                    subtrnod.Text = xmlnod.Name + xmlnod.Value ;
                    partrenod.Nodes.Add(subtrnod);

                    if (xmlnod.ChildNodes.Count > 0)
                    {
                        TransXML(xmlnod.ChildNodes, subtrnod);
                    }
                }
                return 0;
            }
            #endregion

 


        }


}

 

 

 

 

<?xml version="1.0" encoding="utf-8" ?>

<Targ>

  <施工图>
    <SubType>
      <SS1/>
    </SubType>
  </施工图>


  <完工图>
    <SubType>
      <A/>
      <A/>
      <A/>
    </SubType>
  </完工图>

 

</Targ>

 

 

 

 

TREE2 :

 

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Globalization;
using System.Xml;


namespace WindowsFormsApplication7
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
          
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //XmlReader xn = XmlReader.Create(@"..\..\XML.xml");

            TreeExXMLCls a = new TreeExXMLCls();
            a.XMLToTree(@"..\..\XML.xml", treeView1);

        }


        private void populateTreeview()
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Title = "Open XML Document";
            dlg.Filter = "XML Files (*.xml)|*.xml";
            dlg.FileName = Application.StartupPath + "http://www.cnblogs.com/Mayvar/admin/file://XML.xml";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    //Just a good practice -- change the cursor to a
                    //wait cursor while the nodes populate
                    this.Cursor = Cursors.WaitCursor;
                    //First, we'll load the Xml document
                    XmlDocument xDoc = new XmlDocument();
                    xDoc.Load(dlg.FileName);
                    //Now, clear out the treeview,
                    //and add the first (root) node
                    treeView2.Nodes.Clear();
                    treeView2.Nodes.Add(new
                      TreeNode(xDoc.DocumentElement.Name));
                    TreeNode tNode = new TreeNode();
                    tNode = (TreeNode)treeView2.Nodes[0];
                    //We make a call to addTreeNode,
                    //where we'll add all of our nodes
                    addTreeNode(xDoc.DocumentElement, tNode);
                    //Expand the treeview to show all nodes
                    treeView2.ExpandAll();
                }
                catch (XmlException xExc)
                //Exception is thrown is there is an error in the Xml
                {
                    MessageBox.Show(xExc.Message);
                }
                catch (Exception ex) //General exception
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    this.Cursor = Cursors.Default; //Change the cursor back
                }
            }
        }

        private void addTreeNode(XmlNode xmlNode, TreeNode treeNode)
        {
            XmlNode xNode;
            TreeNode tNode;
            XmlNodeList xNodeList;
            if (xmlNode.HasChildNodes) //The current node has children
            {
                xNodeList = xmlNode.ChildNodes;
                for (int x = 0; x <= xNodeList.Count - 1; x++)
                //Loop through the child nodes
                {
                    xNode = xmlNode.ChildNodes[x];
                    treeNode.Nodes.Add(new TreeNode(xNode.Name));
                    tNode = treeNode.Nodes[x];
                    addTreeNode(xNode, tNode);
                }
            }
            else //No children, so add the outer xml (trimming off whitespace)
                //treeNode.Text = xmlNode.InnerXml.Trim();
                treeNode.Text = xmlNode.Value;
              
        }

        private void button2_Click(object sender, EventArgs e)
        {
            populateTreeview();
        }

 

    }
}

 


 

posted on 2012-09-17 06:22  Mayvar  阅读(332)  评论(0编辑  收藏  举报

导航