从对话框中请求的C#中的XML文件中获取信息

时间:2018-07-17 08:00:17

标签: c# xml winforms

我正在尝试解析/获取保存设置值的XML文件的信息。

我想打开一个对话框,用户可以在其中选择.xml文件,然后获取信息并加载设置。

XML文件如下所示:

<?xml version="1.0" encoding="utf-8" ?>
<Configuration version="1.2" createDate="2018-07-17T10:00:00">
    <AutoScale>1</Autoscale>
    <Threshold>2142</Threshold>
    <MinAuto>14</MinAuto>
    <MinMan>1</MinMan>
    <MaxMan>1</MaxMan>
    <BlueBackground>1</BlueBackground>
    <Contour>1</Contour>
    <Rotate>180</Rotate>
    <Flip>Vertical</Flip>
</Configuration>

我的代码(在C#中)如下:

using (var openFileDialogXML = new OpenFileDialog()){
      System.IO.Stream myStream = null;
      openFileDialogXML.InitialDirectory = @System.Environment.CurrentDirectory;
      openFileDialogXML.Filter = "xml files (*.xml)|*.xml|All files (*.*)|*.*";
      openFileDialogXML.FilterIndex = 1;
      openFileDialogXML.RestoreDirectory = true;

      DialogResult dr = openFileDialogXML.ShowDialog();

      if (dr == System.Windows.Forms.DialogResult.OK)
      {
            using (XmlReader reader = XmlReader.Create(openFileDialogXML.FileName))
            {
                 reader.MoveToContent();
                 var version = reader.GetAttribute("version");
                 while (reader.Read())
                 {
                     if (reader.NodeType == XmlNodeType.Element)
                     {
                          switch (reader.Name)
                          {
                               case "AutoScale":
                                    //Get AutoScale value
                                    break;
                               case "Threshold":
                                    break;
                               case "MinAuto":
                                    break;
                               case "MinMan":
                                    break;
                               case "MaxMan":
                                    break;
                               }

                            }
                        }
                    }

我愿意使用任何解析器,但是我希望逐个阅读它,因为将来可能会添加新的设置。

您能帮我/给我一些有关如何实现此目标的建议吗?

3 个答案:

答案 0 :(得分:1)

我喜欢使用Xml Linq并将结果放入字典中,因此当添加新项目时,xml解析器不必更改:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication53
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            Dictionary<string, string> dict = doc.Element("Configuration").Elements()
                .GroupBy(x => x.Name.LocalName, y => (string)y)
                .ToDictionary(x => x.Key, y => y.FirstOrDefault());

        }
    }
}

答案 1 :(得分:0)

我建议使用DataContract并将XML加载到指定的对象中。当您的配置文件更改时,您还需要更新实体。

[DataContract]
public class MyXmlClass
{
    [DataMember]
    public int PropertyToSerialize { get; set; }
}

然后您可以按照此处所述使用DataContractSerializer-https://docs.microsoft.com/en-us/dotnet/framework/wcf/feature-details/serialization-and-deserialization

与手动处理XML相比,使用对象要容易得多:)

答案 2 :(得分:0)

如果您想手动解析它,则需要一些快速而肮脏的答案:

using System.Xml;

[...]

XmlTextReader xtr = new XmlTextReader(GetResourceStream("config.xml"));
while (xtr.Read())
{
if (xtr.AttributeCount == 0)
    continue;

if (xtr.LocalName == "Configuration")
{
    string version = xtr.GetAttribute("version");
    string date = xtr.GetAttribute("createDate");
    Console.WriteLine($"version={version} - date = {date}")
}
else if (xtr.LocalName == "AutoScale")
{
    string autoscale = xtr.ReadString();
    Console.WriteLine($"autoscale={autoscale}")
}

[...]

}
xtr.Close();

如果您需要更多的内容,请先阅读XmlTextReader示例或文档(stackoverflow应该有很多),我没有尝试过代码