简体   繁体   中英

Get information from XML file in C# requested in dialog

I'm trying to parse/get the information of an XML file where I have saved the setting values.

I would like to open a dialog, where the user can select the .xml file and after that get the information and load the settings.

The XML file looks like this:

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

My code (in C#) looks like this:

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

                            }
                        }
                    }

I'm open to use any parser but I would like to read it element by element because it could happen that we add new settings in the future.

Can you please help me/ give me some advice about how I can reach this?

I like using Xml Linq and putting results into a dictionary so when new items are added the xml parser doesn't have to change :

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());

        }
    }
}

I would suggest to use DataContract and load the XML into specified object. When your configuration file changes, you would need to update also the Entity.

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

You can then use DataContractSerializer as described here - https://docs.microsoft.com/en-us/dotnet/framework/wcf/feature-details/serialization-and-deserialization

It will be much easier for you to work with object than parsing XML manually :)

Some quick and dirty answer if you want to parse it manually:

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();

I didn't try the code, if you need more start by looking XmlTextReader examples or documentation (stackoverflow should have plenty of them)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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