简体   繁体   English

将通用XML列表转换为C#对象

[英]Convert generic XML List to C# object

I have this XML file format (coming from a third party API): 我有这种XML文件格式(来自第三方API):

<root>
    <parameter name="id">189880</parameter>
    <parameter name="target">2c92c0f83ff55b4b014007d6194e1bed</parameter>
    <parameter name="account">2c92c0f93fd531f1013feed6c1095259</parameter>
    <parameter name="contact">Laurie</parameter>
</root>

This file can contains between 1 and 50 lines describing a different property for each line. 该文件可以包含1到50行,每行描述一个不同的属性。

I want to dynamically convert it to a C# object. 我想将其动态转换为C#对象。 Each line of the file will become a property and be populated by the corresponding value. 文件的每一行将成为一个属性,并由相应的值填充。

Example based on the XML above: 基于上述XML的示例:

public class Result
{
    public string id { get; set; }
    public string target { get; set; }
    public string account { get; set; }
    public string contact { get; set; }
}

Edit : 编辑:

Let's simplify the problem. 让我们简化问题。 Let's assume that the file structure is fixed (for example always the 4 lines attributes described above ) 让我们假设文件结构是固定的(例如,总是上述4行属性)

Use Xsd.exe tool to generate C# class from XML. 使用Xsd.exe工具从XML生成C#类。 Then use XmlSerializer to deserialize object. 然后使用XmlSerializer反序列化对象。

如果属性会动态更改,最好使用带有Dictionary<T,T>键/值对Dictionary<T,T>Dictionary<T,T> -http://msdn.microsoft.com/zh-cn/library/xfhwa508.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM