简体   繁体   中英

Convert generic XML List to C# object

I have this XML file format (coming from a third party 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.

I want to dynamically convert it to a C# object. Each line of the file will become a property and be populated by the corresponding value.

Example based on the XML above:

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 )

Use Xsd.exe tool to generate C# class from XML. Then use XmlSerializer to deserialize object.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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