如何在C#中将XML转换为Object格式

时间:2015-05-14 05:41:31

标签: c# asp.net asp.net-mvc

我想将此XML转换为对象格式

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

2 个答案:

答案 0 :(得分: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

也可以通过使用Generics进行重构来使其成为通用的。

答案 1 :(得分: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();
    }
}

要从保存的文件创建对象,请添加以下函数,并将[ObjectType]替换为要创建的对象类型。

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