简体   繁体   中英

Convert XML string to generic list C#

I have different xml string which should be mapped to different object, Like we convert json string to generic list is there any way to convert xml string to generic list without specifying the tag names. See json deserialize code:

public List<T> DeSerialize<T>(string input)
{
    var serializer = new DataContractJsonSerializer(typeof(List<T>));

    using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(input)))
    {
        return (List<T>)serializer.ReadObject(ms);
    }
}

The above code will deserialize to generic list if the property name of the object and json name are same.

The code I have now will convert to a specific type not generic list See code below. This should be done without specifying extra property attributes to map xmlnode. Please suggest a generic solution.

public static T FromXmlString<T>(string xmlString)
{
    var reader = new StringReader(xmlString);
    var serializer = new XmlSerializer(typeof(T));
    var instance = (T)serializer.Deserialize(reader);

    return instance;
}

You can follow this way:

  1. Open Developer Command Prompt You can find it in Start Menu > Programs > Microsoft Visual Studio 2012 > Visual Studio Tools Or if you have Windows 8 can just start typing Developer Command Prompt in Start screen
  2. Change location to your XML file directory by typing cd /D "C:\\path\\to\\xml"
  3. Create XSD file from your xml file by typing xsd file.xml
  4. Create C# classes by typing xsd /c file.xsd

And that's it! You have generated C# classes from xml file in C:\\path\\to\\xml\\file.cs

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