I would like to find a way to convert this xml to c# class with all the fields and data into class., something like class bookstore has a book class which has fields like title, year, price, and on. i also need data in the class, is it possible?
XML serialization is built into .net pretty well. Take a look at the XMLSerializer for documentation. It will serialize a class out to XML, or read an XML stream into a class. Only caveat is you need to have the class in your code before you deserialize.
Very concise write up
http://geekswithblogs.net/TimH/archive/2006/02/09/68857.aspx
Of course, if you don't really care about storng typing the objects that are deserialized from XML, you can always treat them as plain objects, and use Reflection to access properties and values. Doesn't sound like much fun either.
in my case, i only have an xml file, so i will have to generate c# class and then fill into data based on the xml file. so, just like you said, the classed are generated dyncmicly, but only the first time, i guess..
FWIW, in OOP, a class is generally simply a mapping to a real world
entity.
looking at your XML, the entity (i.e. thing) is a book. this example code runs in LINQPad 4*:
void Main()
{
List<Book> books = new List<Book>();
// read XML line by line ~~ until no more XML left to read
// when line contains book, extract value of category attribute
Book book = new Book();
book.Category = "CHILDREN";
// when line contains title, extract value of title node
book.Title = "Harry Potter ...";
// when line contains author, extract value of author node
book.Author = "J. K. Rowling";
// when line contains year, extract value of year node
book.YearPublished = 2003;
// when line contains price, extract value of price node
book.Price = 29.99;
// when line contains </book>, add the current object instance to your List<Book>
books.Add(book);
Console.WriteLine (book);
}
public class Book
{
public string Category { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public Int32 YearPublished { get; set; }
public double Price { get; set; }
}
Please note: this is a simplification.
TIMTOWTDI =. there is more than one way to do it
FWIW, my approach, especially with non-complex XML schema like yours, is to avoid heavy weight .NET System.XML classes where simple string methods are sufficient.
Unless you can guarantee that your input XML data is perfect, you need to
validate it.
g.
* if you do not have LINQPad 4:
TOOLS ... get yourself a FREE copy of LINQPad 4 (http://linqpad.net) .. Joe Albahari's LINQPad 4 is an awesome programmer's scratch pad that enables you to quickly check out code snippets you find in books and on web sites
plus LINQPad also lets you rapidly experiment with c# ideas before committing them to vs2010.
LINQPad 4 supports c#, F#, SQL, vb.
B-) Please help me by completing my school survey about computer programmers on my website. Thank you!!! Gerry Lowry +1 705-429-7550 wasaga beach, ontario, canada
yes. Using System.Xml.Serialization.XmlSerializer. Here is some sample code:
using System;
using System.IO;
using System.Xml.Serialization;
namespace Holmok.Utilities
{
public class serial
{
public static void ObjectToXml(object obj, string path_to_xml)
{
//serialize and persist it to it's file
try
{
XmlSerializer ser = new XmlSerializer(obj.GetType());
FileStream fs = File.Open(
path_to_xml,
FileMode.OpenOrCreate,
FileAccess.Write,
FileShare.ReadWrite);
ser.Serialize(fs,obj);
}
catch (Exception ex)
{
throw new Exception(
"Could Not Serialize object to " + path_to_xml,
ex);
}
}
}
}
Thank you for your answer. The class, book, is needed to be generated by xml dynamically. Lets say if the xml does not have a price, then the book class should not have a field - price. The requirement is to create a or many classes based on the xml structure.
btw, this is not homework assignment. this is part of my work. I am researching the best way to do this now. thank you.
you're welcome ... imho, you appear not to understand your own problem, or, at the very least, you are choosing the wrong words to describe your problem.
generally, a class is a template for modeling
something that might exist in the real world such as a book.
example:
public class Book
{
public string Category { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public Int32 YearPublished { get; set; }
public double Price { get; set; }
}
Let's pretend that it's dynamicallypossible to generate a class from XML (for all intents and purposes, it is because it's possible to generate code dynamically at runtime).
justindongqiang
if the xml does not have a price, then the book class should not have a field - price.
now we would have multiple classes ALL with the same name. examples:
public class Book
{
public string Category { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public Int32 YearPublished { get; set; }
}
public class Book
{
public string Category { get; set; }
public string Title { get; set; }
public string Author { get; set; }
}
public class Book
{
public string Category { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public double Price { get; set; }
}
et cetera
imho, what i think you mean is that you want a database schema that can handle this ... is that correct?
justindongqiang
The requirement is to create a or many classes based on the xml structure
QUESTIONS:
(a) why?????????
(b) if you could create many classes ... how would you use them after you've created them? i.e., what is your
goal?
g.
B-) Please help me by completing my school survey about computer programmers on my website. Thank you!!! Gerry Lowry +1 705-429-7550 wasaga beach, ontario, canada
justindongqi...
Member
513 Points
149 Posts
is it possible to convert a xml to c# classes?
Feb 24, 2012 07:39 PM|LINK
lets say i have a xml file which contains node and data, something like this:
<bookstore>
<book category="CHILDREN">
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title>Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
I would like to find a way to convert this xml to c# class with all the fields and data into class., something like class bookstore has a book class which has fields like title, year, price, and on. i also need data in the class, is it possible?
does anyone has any ideas for this?
thanks very much in advance.
Justin
texx
Contributor
2412 Points
415 Posts
Re: is it possible to convert a xml to c# classes?
Feb 24, 2012 08:05 PM|LINK
XML serialization is built into .net pretty well. Take a look at the XMLSerializer for documentation. It will serialize a class out to XML, or read an XML stream into a class. Only caveat is you need to have the class in your code before you deserialize. Very concise write up http://geekswithblogs.net/TimH/archive/2006/02/09/68857.aspx
If you need to be dynamic, as in you don't know what fields the Book class is going to have, I guess you will need to read in the schema for the XML, and build your class at runtime. Ugh, that doesn't sound like fun. Here is a page on dynamic c# classes http://social.msdn.microsoft.com/Forums/eu/csharpgeneral/thread/abff98e3-93fe-44fa-bfd4-fcfe297dbc43
Of course, if you don't really care about storng typing the objects that are deserialized from XML, you can always treat them as plain objects, and use Reflection to access properties and values. Doesn't sound like much fun either.
justindongqi...
Member
513 Points
149 Posts
Re: is it possible to convert a xml to c# classes?
Feb 24, 2012 08:24 PM|LINK
Thank you texx...
in my case, i only have an xml file, so i will have to generate c# class and then fill into data based on the xml file. so, just like you said, the classed are generated dyncmicly, but only the first time, i guess..
is there anyway to do this?
Thasnks
gerrylowry
All-Star
20577 Points
5721 Posts
Re: is it possible to convert a xml to c# classes?
Feb 25, 2012 04:16 PM|LINK
@ justindongqiang
is this a homework assignment?
perhaps i do not understand your question.
FWIW, in OOP, a class is generally simply a mapping to a real world entity.
looking at your XML, the entity (i.e. thing) is a book. this example code runs in LINQPad 4*:
void Main() { List<Book> books = new List<Book>(); // read XML line by line ~~ until no more XML left to read // when line contains book, extract value of category attribute Book book = new Book(); book.Category = "CHILDREN"; // when line contains title, extract value of title node book.Title = "Harry Potter ..."; // when line contains author, extract value of author node book.Author = "J. K. Rowling"; // when line contains year, extract value of year node book.YearPublished = 2003; // when line contains price, extract value of price node book.Price = 29.99; // when line contains </book>, add the current object instance to your List<Book> books.Add(book); Console.WriteLine (book); } public class Book { public string Category { get; set; } public string Title { get; set; } public string Author { get; set; } public Int32 YearPublished { get; set; } public double Price { get; set; } }Please note: this is a simplification.
TIMTOWTDI =. there is more than one way to do it
FWIW, my approach, especially with non-complex XML schema like yours, is to avoid heavy weight .NET System.XML classes where simple string methods are sufficient.
Yon can also use classes like http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.aspx, depending upon your own preferences.
Unless you can guarantee that your input XML data is perfect, you need to validate it.
g.
* if you do not have LINQPad 4:
TOOLS ... get yourself a FREE copy of LINQPad 4 (http://linqpad.net) .. Joe Albahari's LINQPad 4 is an awesome programmer's scratch pad that enables you to quickly check out code snippets you find in books and on web sites plus LINQPad also lets you rapidly experiment with c# ideas before committing them to vs2010.
LINQPad 4 supports c#, F#, SQL, vb.
srinanthuram
Contributor
6800 Points
1549 Posts
Re: is it possible to convert a xml to c# classes?
Feb 25, 2012 07:10 PM|LINK
hi
yes. Using System.Xml.Serialization.XmlSerializer. Here is some sample code:
using System; using System.IO; using System.Xml.Serialization; namespace Holmok.Utilities { public class serial { public static void ObjectToXml(object obj, string path_to_xml) { //serialize and persist it to it's file try { XmlSerializer ser = new XmlSerializer(obj.GetType()); FileStream fs = File.Open( path_to_xml, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite); ser.Serialize(fs,obj); } catch (Exception ex) { throw new Exception( "Could Not Serialize object to " + path_to_xml, ex); } } } }http://www.codeguru.com/forum/showthread.php?t=441772justindongqi...
Member
513 Points
149 Posts
Re: is it possible to convert a xml to c# classes?
Feb 26, 2012 05:13 AM|LINK
Thank you for your answer. The class, book, is needed to be generated by xml dynamically. Lets say if the xml does not have a price, then the book class should not have a field - price. The requirement is to create a or many classes based on the xml structure. btw, this is not homework assignment. this is part of my work. I am researching the best way to do this now. thank you.
gerrylowry
All-Star
20577 Points
5721 Posts
Re: is it possible to convert a xml to c# classes?
Feb 26, 2012 06:22 AM|LINK
@ justindongqiang
you're welcome ... imho, you appear not to understand your own problem, or, at the very least, you are choosing the wrong words to describe your problem.
generally, a class is a template for modeling something that might exist in the real world such as a book.
example:
public class Book { public string Category { get; set; } public string Title { get; set; } public string Author { get; set; } public Int32 YearPublished { get; set; } public double Price { get; set; } }Let's pretend that it's dynamically possible to generate a class from XML (for all intents and purposes, it is because it's possible to generate code dynamically at runtime).
now we would have multiple classes ALL with the same name. examples:
public class Book { public string Category { get; set; } public string Title { get; set; } public string Author { get; set; } public Int32 YearPublished { get; set; } }public class Book { public string Category { get; set; } public string Title { get; set; } public string Author { get; set; } }public class Book { public string Category { get; set; } public string Title { get; set; } public string Author { get; set; } public double Price { get; set; } }et cetera
imho, what i think you mean is that you want a database schema that can handle this ... is that correct?
QUESTIONS:
(a) why?????????
(b) if you could create many classes ... how would you use them after you've created them? i.e., what is your goal?
g.