繁体   English   中英

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

[英]Get information from XML file in C# requested in dialog

我正在尝试解析/获取保存设置值的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;
                               }

                            }
                        }
                    }

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

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

我喜欢使用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());

        }
    }
}

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

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

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

与使用对象相比,使用对象要容易得多:)

如果您想手动解析它,可以使用一些快速而肮脏的答案:

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应该有很多)

暂无
暂无

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

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