读取xml动态创建控件
from1.cs:
public partial class Form1 : Form { public Form1() { int x = 0; int y = 0; XmlDocument Xd = new XmlDocument(); Xd.Load("D:\\config.xml"); XmlNode testNode = Xd.SelectSingleNode("Test"); XmlNodeList list = testNode.SelectNodes("template"); foreach (XmlNode xn in list) { string name = xn.SelectSingleNode("name").InnerText.Trim(); Button button = new Button { Text = name, Width = 250, Height = 75, Left = x + 20, Top = y, }; button.Click += new EventHandler(Button_Click); Controls.Add(button); y += button.Height + 5; } InitializeComponent(); } private void Button_Click(object sender, EventArgs e) { Form4 form = new Form4(); Button b = sender as Button; string name = b.Text; Create(form, name); form.ShowDialog(); } private void Create(Form form, string name) { int x = 0; int y = 0; XmlDocument Xd = new XmlDocument(); Xd.Load("D:\\config.xml"); XmlNode testNode = Xd.SelectSingleNode("Test"); XmlNodeList list = testNode.SelectNodes("template"); foreach (XmlNode node in list) { foreach (XmlNode xnode in node.ChildNodes) { if (xnode.InnerText == name) { XmlNode newnode = xnode.ParentNode; foreach (XmlNode itemnode in newnode.ChildNodes) { if (itemnode.Name == "item") { Label label = new Label { Text = itemnode.InnerText, Width = 250, Height = 75, Left = x + 20, Top = y, }; form.Controls.Add(label); y += label.Height + 5; } } } } } } }
config.xml:
<Test> <template id="Some Template ID"> <name>Template name</name> <description>Discription of this template</description> <item id="1">1st item of this template</item> <item id="2">2nd item of this template</item> <item id="3">3rd item of this template</item> <item id="4">4th item of this template</item> </template> <template id="Another Template ID"> <name>Another template name</name> <description>Discription of this template</description> <item id="1">1st item of another template</item> <item id="2">2nd item of another template</item> <item id="3">3rd item of another template</item> <item id="4">4th item of another template</item> </template> </Test>
Result:
把圈子变小,把语言变干净,把成绩往上提,把故事往心里收,现在想要的以后你都会有。