如何将XML文件中的值复制到c#中的变量

时间:2014-04-01 19:52:36

标签: c# xml linq

我有一个像这样的* .XMl文件:

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

我想将每个“路径”放到变量中。 例如“String user_id = C:\ Windows_default.pif”我有以下代码来读取XML文件。

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

请帮帮我

2 个答案:

答案 0 :(得分:0)

在这种情况下,您可以使用Dictionary<string,string>,哪些键是元素名称,值是路径:

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

然后您可以通过它的元素名称访问每个路径。例如:settings["Users_ID"]将返回C:\Windows\_default.pif

答案 1 :(得分:0)

如果这些是XML中的静态字段,您可以使用DataContractSerializer(或XMLSerializer)序列化到类......

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

(还需要添加对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
    }
}