基于XML中的节点创建用户表单

时间:2019-02-18 13:23:12

标签: c# visual-studio-2017

我在其中一种用户窗体上生成了异常的按钮。这些按钮是基于xml文件中的节点生成的。

    namespace e2e_template
{
    public partial class Form3 : Form
    {
        public Form3(string data)
        {
            string Username = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();

           string Result = Username.Length <= 4 ? "" : Username.Substring(4);


            string Path = $"C:\\Users\\{Result}\\Documents\\template\\config.xml";
            //MessageBox.Show(Path);

            XmlDocument doc = new XmlDocument();
            doc.Load(Path);
            XmlNodeList templates = doc.SelectNodes("//template");


            int x = 10;
            int y = 10;


           foreach (XmlNode template in templates)
            {
                string name = template.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();
        form.ShowDialog();
    }
    }

}

当我单击一个按钮并打开一个新的用户窗体(在本例中为form4)时,我希望在其他节点之间显示文本。但是XML文件中很少有“模板”节点。 XML文件如下所示:

<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>

因此,如果我单击带有标题的按钮,例如“模板名称”,它将像现在一样打开用户form4,但是我会看到项目ID在另一个下面列出了1。但棘手的部分是ID的数量不同。我的意思是可以有4个,也可以有10个。我应该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

首先, 创建一个课程,

public class Item
{
    public string Id { get; set; }
    public string Name { get; set; }
}

在您的Form4中创建一个公共属性,例如

 public string Description { get; set; }
 public List<Item> Items { get; set; }

然后按如下所示修改您的代码,以获取特定模板到Form4的详细信息

private void Button_Click(object sender, EventArgs e)
{
    XDocument xDoc = XDocument.Load(@"Path to your xml file");

    string buttonText = (sender as Button).Text;

    string description = xDoc.Descendants("template").Where(x => x.Element("name").Value == buttonText).Select(x => x.Element("description").Value).FirstOrDefault();

    var listofItems = xDoc.Descendants("template").Where(x => x.Element("name").Value == buttonText).SelectMany(x => x.Elements("item")).Select(y => new Item { Id = y.Attribute("id").Value, Name = y.Value });

    Form4 form = new Form4();

    form.Description = description;
    form.Items = listofItems.ToList();

    form.ShowDialog();
}

现在,“描述”和“项目”在Form4上具有值,然后您就可以使用它了。

相关问题