[英]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. 我正在尝试解析/获取保存设置值的XML文件的信息。
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. 我想打开一个对话框,用户可以在其中选择.xml文件,然后获取信息并加载设置。
The XML file looks like this: 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>
My code (in C#) looks like this: 我的代码(在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;
}
}
}
}
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 : 我喜欢使用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());
}
}
}
I would suggest to use DataContract
and load the XML into specified object. 我建议使用
DataContract
并将XML加载到指定的对象中。 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 然后,您可以按照此处所述使用
DataContractSerializer
- https://docs.microsoft.com/zh-cn/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) 我没有尝试过代码,如果您需要更多的内容,可以先看XmlTextReader示例或文档(stackoverflow应该有很多)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.