Generate object from xml in c#
To generate objects from an XML document in C#, you typically use XML serialization—a built-in feature of the .NET framework. The main class involved is XmlSerializer.
Generating C# Object from XML document
1. Define a C# class matching the XML structure
Suppose your XML looks like this:
<Person>
<Name>John</Name>
<Age>30</Age>
</Person>
Create a corresponding class:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
2. Deserialize XML into an object
Use XmlSerializer to convert XML into your object:
using System;
using System.IO;
using System.Xml.Serialization;
class Program
{
static void Main()
{
var serializer = new XmlSerializer(typeof(Person));
using (var reader = new StreamReader("person.xml"))
{
Person person = (Person)serializer.Deserialize(reader);
Console.WriteLine(person.Name);
}
}
}
3. Deserialize from a string instead of a file
string xml = @"John30";
var serializer = new XmlSerializer(typeof(Person));
using (var reader = new StringReader(xml))
{
Person person = (Person)serializer.Deserialize(reader);
}
4. Handle attributes or different XML shapes
If your XML uses attributes:
<Person Name="John" Age="30" />
Use attributes like this:
public class Person
{
[XmlAttribute]
public string Name { get; set; }
[XmlAttribute]
public int Age { get; set; }
}
5. Generate classes automatically from XML (optional)
If you don’t want to write classes manually, you can use:
• xsd.exe (older but still usable)
• Visual Studio’s “Paste XML as Classes” feature
Example workflow with xsd.exe:
• Convert XML → XSD
• Generate classes from XSD
Common pitfalls
• XML element names must match property names (or use [XmlElement("Name")])
• Root element must match the class (or use [XmlRoot])
• Collections need List or arrays
• Classes must be public and have parameterless constructors
Other Examples of Object Generation from XML
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:
<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;
}
}
}