Why does the OnDeserialization not fire for XML Deserialization?
There’s no equivalent of OnDeserialized for XML deserialization. See this post for workarounds: How do you find out when you’ve been loaded via XML Serialization?
There’s no equivalent of OnDeserialized for XML deserialization. See this post for workarounds: How do you find out when you’ve been loaded via XML Serialization?
The following should serialize properly the way you want. The clue being [XmlElement(“credentials”)] on the list. I did this by taking your xml, generating a schema (xsd) from it in Visual Studio. Then running xsd.exe on the schema to generate a class. (And some small edits) public class CredentialsSection { public string Username { get; … Read more
Take 2 – let’s implement this ourselves using the unknown element handling event (see the comments below for some limitations though): public class XmlSynonymDeserializer : XmlSerializer { public class SynonymsAttribute : Attribute { public readonly ISet<string> Names; public SynonymsAttribute(params string[] names) { this.Names = new HashSet<string>(names); } public static MemberInfo GetMember(object obj, string name) { … Read more
xmltodict (full disclosure: I wrote it) does exactly that: xmltodict.parse(“”” <?xml version=”1.0″ ?> <person> <name>john</name> <age>20</age> </person>”””) # {u’person’: {u’age’: u’20’, u’name’: u’john’}}
You can encapsulate the list trivially: using System; using System.Collections.Generic; using System.Xml.Serialization; [XmlRoot(“user_list”)] public class UserList { public UserList() {Items = new List<User>();} [XmlElement(“user”)] public List<User> Items {get;set;} } public class User { [XmlElement(“id”)] public Int32 Id { get; set; } [XmlElement(“name”)] public String Name { get; set; } } static class Program { static … Read more
Your classes should look like this [XmlRoot(“StepList”)] public class StepList { [XmlElement(“Step”)] public List<Step> Steps { get; set; } } public class Step { [XmlElement(“Name”)] public string Name { get; set; } [XmlElement(“Desc”)] public string Desc { get; set; } } Here is my testcode. string testData = @”<StepList> <Step> <Name>Name1</Name> <Desc>Desc1</Desc> </Step> <Step> <Name>Name2</Name> … Read more
How about you just save the xml to a file, and use xsd to generate C# classes? Write the file to disk (I named it foo.xml) Generate the xsd: xsd foo.xml Generate the C#: xsd foo.xsd /classes Et voila – and C# code file that should be able to read the data via XmlSerializer: XmlSerializer … Read more