2010-09-14 18 views
0

我正在使用C#和.NET 3.5框架編寫應用程序。幫助使用帶有枚舉的LINQ和XML

我有一個這樣的枚舉,

public static enum SettingOneType { FooA, FooB, FooC } 

我也有,我加載像這樣的load()方法一個XDocument,

LoadXML(){ 
    ... 
    XDocument SettingsDocument; 
    if(File.Exists(path) 
    { 
    XElement SettingsElement = new XElement("DeviceSettings", 
     new XElement("Setitng1", SettingOneType.FooA.ToString()), 
     new XElement("Setting2", ... )); 


    XDeclaration dec = new XDeclaration("1.0", "UTF-8", "yes"); 
    SettingsDocument = new XDocument(dec, SettingsElement); 
    SettingsDocument.Save(xpath); 
    } 
    else SettingsDocument = XDocument.Load(path); 
} 

我想知道是,是否有一種以強類型方式讀取這些設置的方法。因爲我想在我的應用程序中的屬性,將在這樣的xml文件訪問值...

public SettingOneType SettingOne 
{ 
    get{ 
     SettingOneType x = SettingsDocument. //Here I know I can use LINQ statements to file the value I want but is there a way to cast the value to the correct type without using a giant switch statement or something? 
    } 
} 

注:之前有人建議我使用內置的可用應用設置文件。不要打擾。我通常使用這些,但是對於這個項目,我有一個理由,我不能解釋。

回答

1

具有枚舉值作爲一個字符串,你可以使用Enum.Parse解析它:

string foo = "FooA"; 
SettingOneType settingOneType = 
    (SettingOneType)Enum.Parse(typeof(SettingOneType), foo); 
1

你可以使用某種形式的序列(如DataContractSerializer的)一個類型的對象持久化到XML。然後,您可以以類型安全的方式讀取整個對象,而不是手動處理單個XML節點。

例如,創建一個DocumentSettings類和使用類似於下面的代碼就堅持到XML:

internal string Serialize(Object documentSettings) 
{ 
    StringBuilder serialXML = new StringBuilder(); 
    DataContractSerializer dcSerializer = new DataContractSerializer(obj.GetType()); 
    using (XmlWriter xWriter = XmlWriter.Create(serialXML)) 
    { 
     dcSerializer.WriteObject(xWriter, obj); 
     xWriter.Flush(); 
     return serialXML.ToString(); 
    } 
} 

我要把它留給你找出反串行化代碼(它很簡單)

+0

因此,這將讀取並保存所有的設置一次? – PICyourBrain 2010-09-14 14:29:50

+0

是的。我也建議這樣做,除非你有大量的數據,否則它比其他選項更容易 - 那麼也許應該考慮一個替代方案。我的意思是巨大 - XML序列化是_quite_性能。 – 2010-09-14 17:51:49

+0

約旦:是的。更新單個設置通常涉及讀取整個類,更改值並將所有內容序列化迴文件。對於小型課程來說,開銷是相當小的,但顯然如果你的設置文件很大,那麼這不是最好的方法。 – Addys 2010-09-14 20:14:13

0

將XML值存儲爲數字,然後您只需int.parse字符串值,並將其轉換爲枚舉類型。每個枚舉成員默認對應一個int值,並且會進行適當的轉換,默認情況下它們按照它們定義的順序從0增加。

當您創建的值,而不是:

new XElement("Setitng1", SettingOneType.FooA.ToString()) 

做:

new XElement("Setitng1", ((int)SettingOneType.FooA).ToString()) 

然後你看他們回來:

SettingOneType mySetting = (SettingOneType)int.Parse(myXElem.Value); 

您可能能夠只是做一個隱含的投在那裏,我不記得,但這是無論如何jist ..