2015-05-14 50 views
2

我想這個XML中轉換爲對象格式如何將XML轉換成C#對象格式

- <information> 
- <item> 
    <key>Name</key> 
    <value>NameValue</value> 
    </item> 
- <item> 
    <key>Age</key> 
    <value>17</value> 
    </item> 
- <item> 
    <key>Gender</key> 
    <value>MALE</value> 
    </item> 
- </information> 

對象類似,

Person.Name = "Name Value" 
Person.Age = 17 
Person.Gender = "Male" 
+0

如果您需要將xml轉換爲Dictionary對象,則此墨跡可能會重複您正在搜索的內容http://stackoverflow.com/questions/13952425/how-to-convert-xml-to-dictionary – Nivs

+0

如果它是設計時轉換,可以用xsd.exe生成類 – Thangadurai

+0

我覺得這樣會對你有所幫助:http://stackoverflow.com/questions/8950493/converting-xmldocument-to-dictionarystring-string –

回答

0

您可以使用XML反序列化和序列化要做到這一點。

/// <summary> 
/// Saves to an xml file 
/// </summary> 
/// <param name="FileName">File path of the new xml file</param> 
public void Save(string FileName) 
{ 
    using (var writer = new System.IO.StreamWriter(FileName)) 
    { 
     var serializer = new XmlSerializer(this.GetType()); 
     serializer.Serialize(writer, this); 
     writer.Flush(); 
    } 
} 

要創建從保存文件的對象,添加以下功能並且與要創建的對象類型替換[對象類型。

/// <summary> 
/// Load an object from an xml file 
/// </summary> 
/// <param name="FileName">Xml file name</param> 
/// <returns>The object created from the xml file</returns> 
public static [ObjectType] Load(string FileName) 
{ 
    using (var stream = System.IO.File.OpenRead(FileName)) 
    { 
     var serializer = new XmlSerializer(typeof([ObjectType])); 
     return serializer.Deserialize(stream) as [ObjectType]; 
    } 
} 

編號:Serialize an object to XML

+0

對。但請注意,這裏的XML包含「鍵值對」。所以我需要解決方案,如果我可以使用'字典'對象 –

2

您可以XDocument與實現這一目標以下方式反映:我

XDocument XDocument = XDocument.Parse(MyXml); 

var nodes = XDocument.Descendants("item"); 

// Get the type contained in the name string 
Type type = typeof(Person); 

// create an instance of that type 
object instance = Activator.CreateInstance(type); 

// iterate on all properties and set each value one by one 

foreach (var property in type.GetProperties()) 
{ 

    // Set the value of the given property on the given instance 
    if (nodes.Descendants("key").Any(x => x.Value == property.Name)) // check if Property is in the xml 
    { 
     // exists so pick the node 
     var node = nodes.First(x => x.Descendants("key").First().Value == property.Name); 
     // set property value by converting to that type 
     property.SetValue(instance, Convert.ChangeType(node.Element("value").Value,property.PropertyType), null); 
    } 
} 


var tempPerson = (Person) instance; 

取得了Example Fiddle

它也可以通過使用重構它被泛型泛型。