Generate object from xml in c#

Generate object from xml in c#

Assume that you have an xml file including several levels of data and you want to read this xml file into in-memory objects in c# programming language.

Check the contents of xml file given below:

<?xml version="1.0" encoding="UTF-8"?>
<customers>
  <customer>
    <name>Name1</name>
    <surname>Surname1</surname>
  </customer>
  <customer>
    <name>Name2</name>
    <age>Age2</age>
  </customer>
</customers>

Creating C# class file from XML file

You can create a C# class file using xsd command through Developer Command Prompt as given below:

xsd test.xml // will create test.xsd file
xsd test.xsd /classes // will create test.cs file

Loading XML data into C# objects

Then, add test.cs file to your project and use it to load the xml file as given below:

XmlSerializer ser = new XmlSerializer(typeof(customers));
string filename = "test.xml";
var fstream = new FileStream(filename, FileMode.Open);
customers data = ser.Deserialize(fstream) as customers;
if (data != null)
{
    // use your data
}

Note that, there are also several 3rd party tools that are able to create c# class files from given xml files.

Solution 2: Json to create dynamic objects from xml files

XDocument doc = XDocument.Parse(xmlData); // or XDocument.Load(path)
string jsonText = JsonConvert.SerializeXNode(doc);
dynamic dyn = JsonConvert.DeserializeObject<ExpandoObject>(jsonText);

Solution 3: Parsing XML files into dynamic objects in C#

Here is another alternative solution that can be used for parsing xml files to dynamic objects in c#.

public class XmlToDynamic
{
    public static void Parse(dynamic parent, XElement node)
    {
        if (node.HasElements)
        {
            if (node.Elements(node.Elements().First().Name.LocalName).Count() > 1)
            {
                var item = new ExpandoObject();
                var list = new List<dynamic>();
                foreach (var element in node.Elements())
                {                       
                    Parse(list, element);                       
                }

                AddProperty(item, node.Elements().First().Name.LocalName, list);
                AddProperty(parent, node.Name.ToString(), item);
            }
            else
            {
                var item = new ExpandoObject();

                foreach (var attribute in node.Attributes())
                {
                    AddProperty(item, attribute.Name.ToString(), attribute.Value.Trim());
                }

                foreach (var element in node.Elements())
                {
                    Parse(item, element);
                }

                AddProperty(parent, node.Name.ToString(), item);
            }
        }
        else
        {
            AddProperty(parent, node.Name.ToString(), node.Value.Trim());
        }
    }

    private static void AddProperty(dynamic parent, string name, object value)
    {
        if (parent is List<dynamic>)
        {
            (parent as List<dynamic>).Add(value);
        }
        else
        {
            (parent as IDictionary<String, object>)[name] = value;
        }
    }
}


added 6 years 6 months ago

- How to make bold the text before colon character in Microsoft Word
- Generate object from xml in c#
- 24 Useful Distinct Color Codes
- How to draw an arrow with DrawLine command
- How to write Snake game in C#?
- Break Parallel Foreach Earlier
- How to find all Stored Procedures having a given text inside
- How to Create and Write Excel File in C#
- Extension Methods
- Microsoft Code Contracts
- VersaFix
- QuickFIX
- fix4net
- Converting String to Double in C#
- C# File Operations, C# Input Output (C# I/O)
2
1