简体   繁体   中英

How to copy values from XML file to variables in c#

I have an *.XMl file like this :

<?xml version="1.0" encoding="utf-8" ?> 
- <!-- User settings
  --> 
- <Settings>
  <Session_File>C:\programs\Notepad++Portable\help.html</Session_File> 
  <Training_catalogue>C:\Windows\Cursors\aero_ew.cur</Training_catalogue> 
  <Users_ID>C:\Windows\_default.pif</Users_ID> 
  <File_with_badge_ID>C:\Windows\PFRO.log</File_with_badge_ID> 
  <Session_Folder>C:\Program Files</Session_Folder> 
  <PDF_Folder>C:\Program Files\GRETECH\GomPlayer\logos</PDF_Folder> 
  </Settings> 

I would like put each "path" to a variable. For example "String user_id = C:\\Windows_default.pif" I have a following code to read an XML file.

//Read values from xml file
XElement xelement = XElement.Load("settings.xml");
IEnumerable<XElement> employees = xelement.Elements();
// Read the entire XML
foreach (var employee in employees)
{
   Maybe in this place I have to write some code
}

Please help me

You could use a Dictionary<string,string> in this case which keys would be element names and values are paths:

var settings = XDocument.Load("settings.xml").Root
               .Elements()
               .ToDictionary(x => x.Name, x => (string)x);

Then you can access each path by it's element name.For example: settings["Users_ID"] will return C:\\Windows\\_default.pif

If those are static fields in the XML, you can serialize to a class using DataContractSerializer (or XMLSerializer)...

using System.Runtime.Serialization;
using System.IO;

(also need to add the reference to System.Runtime.Serialization)

[DataContract]
public class Settings
{
    [DataMember]
    public string Session_File { get; set; }
    [DataMember]
    public string Training_catalogue { get; set; }
    [DataMember]
    public string Users_ID { get; set; }
    [DataMember]
    public string File_with_badge_ID { get; set; }
    [DataMember]
    public string Session_Folder { get; set; }
    [DataMember]
    public string PDF_Folder { get; set; }

    public static Settings ReadSettings(string Filename)
    {
        using (var stream = new FileStream(Filename, FileMode.OpenOrCreate))
            try
            {
                return new DataContractSerializer(typeof(Settings)).ReadObject(stream) as Settings;
            }
            catch { return new Settings(); }
    }
    public void Save(string Filename)
    {
        using (var stream = new FileStream(Filename, FileMode.Create, FileAccess.Write))
            new DataContractSerializer(typeof(Settings)).WriteObject(stream, this);
    }
    public Settings()
    {
        //defaults
    }
}

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