本文介绍了C#加载XML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建一个Windows窗体通过一个XML文档提供的属性?

How can I create a Windows Form with properties provided by an XML document?

下面就是这样一个XML文档:

Here is such an XML document:

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



在加载的形式,我需要展示的形式和从价值观上的按钮, XML文档。

Upon loading the form, I need to show the form and the button on it with the values from the XML document.

任何人都可以提供关于这个问题的任何帮助或教程?

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:


  • 选择一些控制并转到属性标签

  • 找到 (的applicationSettings)在数据类

  • 开启属性绑定编辑

  • 您要保存属性选择和负载从xml属性并创建该财产

  • Select some control and go to Properties tab
  • Find (ApplicationSettings) property under Data category
  • Open property binding editor
  • Select property you want to save and load from xml and create new setting for that property

如果你确实需要使用XML,那么你应该手工解析它。你可以创建一个像(样带的​​LINQ to XML)部分(扩展)方法:

If you really need to use your xml, then you should parse it manually. You can create some (extension) methods like (sample with Linq to 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

这篇关于C#加载XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 10:31