Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hello All,

I want to populate object (I don't know the object name but it could be collection/Dataset / Datatable or any) from XML .
For example I have below XML
HTML
<Employees Count="2">
 <Employee Code="A" Name="XYZ">
   <Address City="A" Pin="0000"></Address>
   <Contact Mob="123456" Phone="02145235" Email="XYZ@domain.com"></Contact>
 </Employee>
 <Employee Code="B" Name="ABC">
   <Address City="C" Pin="111"></Address>
   <Contact Mob="78794656" Phone="+912546" Email="ABC@domain.com"></Contact>
 </Employee>
</Employees>


in the result of that I want output in any C# object which have like this

HTML
Employees 
   [Count=2]
  Employee    
     [Code=A] [Name=XYZ]
     Address
     [City=A] [Pin=0000]
     Contact 
     [Mob=123456] [Phone=02145235] [Email=XYZ@domain.com]
  Employee
   [Code=B] [Name=ABC]
   Address
   [City=C] [Pin=111]
   Contact
   [Mob=78794656] [Phone=+912546] [Email=ABC@domain.com]


So that I can read through as
MyObject.Employees.Count
MyObject.Employee[0].Code [which will give me A]
MyObject.Employee[1].Code [which will give me B]

...And so on

Amir Mahfoozi do you have any idea
Posted
Updated 15-Dec-11 22:49pm
v2
Comments
Oleksandr Kulchytskyi 1-Jun-12 3:39am    
You can do it by using xml serialization mechanism in NET environment. See link
http://msdn.microsoft.com/ru-ru/library/system.xml.serialization.xmlserializer%28v=vs.90%29.aspx

I hope this will solve your problem:

C#
[XmlRoot("Datatable"), Serializable]
public class Datatable
{
    [XmlElement("Employees")]
    public Employees Employees { get; set; }
}

public class Employees
{
    [XmlAttribute("Count")]
    public int Count { get; set; }
    [XmlElement("Employee")]
    public List<employee> Employee { get; set; }
}

public class Employee
{
    [XmlAttribute("Code")]
    public string Code { get; set; }
    [XmlAttribute("Name")]
    public string Name { get; set; }
    [XmlElement("Address")]
    public Address Address { get; set; }
    [XmlElement("Contact")]
    public Contact Contact { get; set; }
}

public class Address
{
    [XmlAttribute("City")]
    public string City { get; set; }
    [XmlAttribute("Pin")]
    public string Pin { get; set; }
    [XmlText]
    public string AddressValue { get; set; }
}

public class Contact
{
    [XmlAttribute("Mob")]
    public string Mob { get; set; }
    [XmlAttribute("Phone")]
    public string Phone { get; set; }
    [XmlAttribute("Email")]
    public string Email { get; set; }
    [XmlText]
    public string ContactValue { get; set; }
}



To load the object from the file:
C#
XmlSerializer serializer = new XmlSerializer(typeof(Datatable));
FileStream loadStream = new FileStream("sample.xml", FileMode.Open, FileAccess.Read);
Datatable loadedObject = (Datatable)serializer.Deserialize(loadStream);
loadStream.Close();


and sample.xml need to look like this:

XML
<?xml version="1.0"?>
<datatable xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <employees count="2">
    <employee code="A" name="XYZ">
      <address city="A" pin="0000" />
      <contact mob="123456" phone="02145235" email="XYZ@domain.com" />
    </employee>
    <employee code="B" name="ABC">
      <address city="C" pin="111" />
      <contact mob="78794656" phone="+912546" email="ABC@domain.com" />
    </employee>
  </employees>
</datatable>
 
Share this answer
 
v3
Comments
dr.kitanjal 19-Dec-11 0:48am    
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Xml.Serialization;
namespace EMPPRO
{


public partial class Form1 : Form
{

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
FileStream loadStream = new FileStream("ep.xml", FileMode.Open, FileAccess.Read);
Datatable loadedObject = (Datatable)serializer.Deserialize(loadStream);
loadStream.Close();

}
}
}

Here is my main class . I am getting below error . Please suggest

Error 2 The name 'serializer' does not exist in the current context
Drazen Pupovac 19-Dec-11 2:02am    
I forgot to add this line:
XmlSerializer serializer = new XmlSerializer(typeof(Datatable));


private void button1_Click(object sender, EventArgs e)
{
FileStream loadStream = new FileStream("sample.xml", FileMode.Open, FileAccess.Read);
XmlSerializer serializer = new XmlSerializer(typeof(Datatable));
Datatable loadedObject = (Datatable)serializer.Deserialize(loadStream);
loadStream.Close();
}
dr.kitanjal 19-Dec-11 3:10am    
Thanks Now I am getting this error

System.InvalidOperationException was unhandled
Message="There is an error in XML document (2, 2)."
Source="System.Xml"
StackTrace:
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
at System.Xml.Serialization.XmlSerializer.Deserialize(Stream stream)
at Test.Main(String[] args) in C:\Users\rahul.dhoble\AppData\Local\Temporary Projects\ConsoleApplication1\Program.cs:line 62
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.InvalidOperationException
Message="<datatable xmlns=""> was not expected."
Source="cfe6q0aa"
StackTrace:
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderDatatable.Read7_Datatable()
InnerException:


Code is as below :
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

[XmlRoot("Datatable"), Serializable]
public class Datatable
{
[XmlElement("Employees")]
public Employees Employees { get; set; }
}

public class Employees
{
[XmlAttribute("Count")]
public int Count { get; set; }
[XmlElement("Employee")]
public Employee Employee { get; set; }
}

public class Employee
{
[XmlAttribute("Code")]
public string Code { get; set; }
[XmlAttribute("Name")]
public string Name { get; set; }
[XmlElement("Address")]
public Address Address { get; set; }
[XmlElement("Contact")]
public Contact Contact { get; set; }
}

public class Address
{
[XmlAttribute("City")]
public string City { get; set; }
[XmlAttribute("Pin")]
public string Pin { get; set; }
[XmlText]
public string AddressValue { get; set; }
}

public class Contact
{
[XmlAttribute("Mob")]
public string Mob { get; set; }
[XmlAttribute("Phone")]
public string Phone { get; set; }
[XmlAttribute("Email")]
public string Email { get; set; }
[XmlText]
public string ContactValue { get; set; }
}
public class Test
{
public static void Main(string[] args)
{
Console.Write("Hi");
XmlSerializer serializer = new XmlSerializer(typeof(Datatable));
FileStream loadStream = new FileStream("sample.xml", FileMode.Open, FileAccess.Read);
Datatable loadedObject = (Datatable)serializer.Deserialize(loadStream);
loadStream.Close();
Console.ReadKey();
}

}
Drazen Pupovac 19-Dec-11 3:18am    
Problem is in XML file. From some reason he can't read all data.

You can leave me an email and I will send you complete project. I think it will be the easiest way.
MD. Mohiuddin Ahmed 18-Jan-13 6:40am    
Hello , Drazen Pupovac ... It would very be nice of you if you send me the project too ...... I'm having the same problem too....... Thanks... MyEmail : ________________________
Your problem is a well known one, and it is usually addressed via object serialization. See, for instance: "Serialization (C# and Visual Basic)"[^], "How to: Read Object Data from an XML File (C# and Visual Basic)"[^] at MSDN.
 
Share this answer
 
Comments
dr.kitanjal 16-Dec-11 4:48am    
But still here I need to create class of known variable and array and that won't work if my XML node value and attribute changes
Please explain me with some code snippet.
Thanks in advance
i think you can take the help of system.dynamic namespace and dynamic and ExpendoObject classes to load the xml file to create your runtime objects.


http://blogs.captechconsulting.com/blog/kevin-hazzard/fluent-xml-parsing-using-cs-dynamic-type-part-1?cf03388EF1=29488A758!MTA1MDM0ODc3OmNvcnByYWRpdXNzc286EVZo9M86sPZ+IK01HmjHZQ==[^]


link can help you if i understand your requirement correctly.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900