c# - 如何在 C# 中将 XML 转换为对象格式

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

最佳答案

您可以使用反射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/

相关文章:

asp.net-mvc - ASP.NET MVC 2 编辑器模板

asp.net-mvc - MVC中 Controller 如何知道DeleteConfirmed上的Id?

c# - 实现此业务规则的最佳地点?

c# - 在 Blazor 应用程序中使用 Azure Active Directory 时如何在 asp net core 3.1 中自定义注销页面

c# - CRM Online RetrieveMultiple 与 OptionSetValueCollection 条件

c# - 官方推荐的创建 ASP.NET Webforms 应用程序的技术是什么?

asp.net - ajax 日历扩展器中的日期格式 (MM/dd/yyyy)

asp.net - ScriptManager.RegisterStartUpScript(...) 不工作

asp.net-mvc - 无法从 Identity Server 3 获取用户信息

c# - 在本地网络中部署 ASP .NET Web Core 2.0 中的项目