我想将此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"
最佳答案
您可以通过反射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
也可以通过使用泛型对其进行重构来使其通用。
关于c# - 如何在C#中将XML转换为对象格式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30230045/