简体   繁体   English

C#加载XML文件

[英]C# loading a XML file

How can I create a Windows Form with properties provided by an XML document? 如何使用XML文档提供的属性创建Windows窗体?

Here is such an XML document: 这是一个XML文档:

<Form>
   <Size>
     <Width>558</Width> 
     <Height>537</Height> 
   </Size>
   <Text>XML saving</Text> 
   <Name>Form1</Name> 
   <Button>
     <Name>button1</Name> 
     <Text>XML button</Text> 
     <Size>
       <Width>130</Width> 
       <Width>45</Width> 
     </Size>
     <Location>
       <X>14</X> 
       <Y>24</Y> 
     </Location>
   </Button>
 </Form>

Upon loading the form, I need to show the form and the button on it with the values from the XML document. 加载表单后,我需要显示表单以及表单上的按钮以及XML文档中的值。

Can anyone provide any assistance or tutorials on this subject? 任何人都可以提供有关此主题的任何帮助或教程吗?

There is build-in functionality you can use to save and restore form settings. 您可以使用内置功能来保存和还原表单设置。 Use application settings binding . 使用应用程序设置绑定

You can bind such properties as Size, Location, Text, etc of form and it's controls to settings, which will be automatically loaded and applied to controls. 您可以将诸如窗体的大小,位置,文本等属性及其控件绑定到设置,这些设置将自动加载并应用于控件。 Steps: 脚步:

  • Select some control and go to Properties tab 选择一些控件,然后转到“属性”选项卡
  • Find (ApplicationSettings) property under Data category 在数据类别下查找(ApplicationSettings)属性
  • Open property binding editor 打开属性绑定编辑器
  • Select property you want to save and load from xml and create new setting for that property 选择要保存并从xml加载的属性,并为该属性创建新设置

If you really need to use your xml, then you should parse it manually. 如果确实需要使用xml,则应该手动解析它。 You can create some (extension) methods like (sample with Linq to Xml): 您可以创建一些(扩展)方法,例如(使用Linq到Xml进行采样):

public static void ApplySettings(this Button button, XDocument xdoc)
{
    var settings = xdoc
                 .Descendatns("Button")
                 .SingleOrDefault(b => (string)b.Element("Name") == button.Name);

    if (settings == null)
       return;

    button.Text = (string)settings.Element("Text");
    var location = settings.Element("Location");
    if (location != null)
    {
        button.X = (int)location.Element("X");
        button.Y = (int)location.Element("Y");
    }

    //etc
}

And call those method for each control: 并为每个控件调用这些方法:

var xdoc = XDocument.Load(settings_file);
button1.ApplySettings(xdoc);
// etc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM