当前位置: 编程技术>.net/c#/asp.net
c# winform读取xml文件创建菜单的代码
来源: 互联网 发布时间:2014-10-23
本文导语: 代码如下: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 WinformMenu.Helper;using System.Xml;namespace WinformMenu{ public partial class FrmAddMenu : For...
代码如下:
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 WinformMenu.Helper;
using System.Xml;
namespace WinformMenu
{
public partial class FrmAddMenu : Form
{
public FrmAddMenu()
{
InitializeComponent();
}
private void FrmAddMenu_Load(object sender, EventArgs e)
{
MenuStrip menuS = new MenuStrip();
menuS.Parent = this;
string xmlFileName = @"F:c#工程WinformMenuWinformMenuXML菜单.xml";
createMenu(xmlFileName, menuS);
}
public void createMenu(string xmlFileName, MenuStrip menuS)
{
//1:根据XmlElement创建菜单
//XmlNode node = xmlHelper.GetXmlNode(xmlFileName, "//MangeTvMenu");
//foreach (XmlNode xml in node.ChildNodes)
//{
// ToolStripMenuItem mainMenu=new ToolStripMenuItem();
// mainMenu.Text = xml.Attributes["descript"].Value;
// menuS.Items.Add(mainMenu);
// if (xml.HasChildNodes)
// {
// CreateSubMenuByNode(xml, mainMenu);
// }
//}
//2:根据XmlNode创建菜单
XmlElement xml = xmlHelper.GetXmlElement(xmlFileName);
foreach (XmlElement xel in xml.ChildNodes)
{
ToolStripMenuItem mainMenu = new ToolStripMenuItem();
mainMenu.Text = xel.Attributes["descript"].Value;
menuS.Items.Add(mainMenu);
if (xml.HasChildNodes)
{
CreateSubMenuByElement(xel, mainMenu);
}
}
}
///
/// 根据node节点递归创建菜单
///
///
///
public void CreateSubMenuByNode(XmlNode xNode, ToolStripMenuItem menuItem)
{
foreach (XmlNode xml in xNode.ChildNodes)
{
ToolStripMenuItem subMenu = new ToolStripMenuItem();
if (xml.ChildNodes.Count > 1)
{
subMenu.Text = xml.Attributes["descript"].Value;
menuItem.DropDown.Items.Add(subMenu);
CreateSubMenuByNode(xml, subMenu);
}
else
{
subMenu.Text = xml.InnerText;
menuItem.DropDown.Items.Add(subMenu);
}
}
}
///
/// 根据元素节点递归创建菜单
///
///
///
public void CreateSubMenuByElement(XmlElement xml, ToolStripMenuItem menuItem)
{
foreach (XmlElement xel in xml.ChildNodes)
{
ToolStripMenuItem subMenu = new ToolStripMenuItem();
if (xel.ChildNodes.Count>1)
{
subMenu.Text = xel.Attributes["descript"].Value;
menuItem.DropDown.Items.Add(subMenu);
CreateSubMenuByElement(xel, subMenu);
}
else
{
subMenu.Text = xel.InnerText;
menuItem.DropDown.Items.Add(subMenu);
}
}
}
///////////////////////////////////////////////////
}
}
xml文件格式如下:
代码如下:
员工
部门
个人基本信息
学历信息
婚姻信息
部门1
部门2
基本工资
绩效工资
加班
请假
加薪
其他