Split XML string into class in C #?

Possible duplicate:
How to deserialize an XML document

Suppose I have a class defined in C #:

public class Book { public string Title {get; set;} public string Subject {get; set;} public string Author {get; set;} } 

Suppose I have XML that looks like this:

 <Book> <Title>The Lorax</Title> <Subject>Children Literature</Subject> <Author>Theodor Seuss Geisel</Author> <Book> 

If I would like to instantiate the Book class using this XML, the only way I know this is to use the XML Document class and list the XML nodes.

Does the .NET Framework provide any way to create classes using XML? If not, what are the best methods for doing this?

+8
c # xml class
source share
2 answers

You can simply use XML serialization to instantiate a class from XML:

 XmlSerializer serializer = new XmlSerializer(typeof(Book)); using (StringReader reader = new StringReader(xmlDocumentText)) { Book book = (Book)(serializer.Deserialize(reader)); } 
+37
source share

There are several ways to deserialize an XML document - the XmlSerializer living in System.Xml.Serialization , and the new DataContractSerializer , which is located in System.Runtime.Serialization .

Both require that you decorate members of your class with attributes that talk about how to work with the serializer (different attributes for each).

+8
source share

All Articles