Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse XML string to class in C#? [duplicate]

Tags:

c#

.net

class

xml

Possible Duplicate:
How to Deserialize XML document

Suppose that I have a class that is defined like this in C#:

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

Suppose that I have XML that looks like this:

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

If I would like to instantiate an instance of the Book class using this XML, the only way I know of to do this is to use the XML Document class and enumerate the XML nodes.

Does the .net framework provide some way of instantiating classes with XML code? If not, what are the best practices for accomplishing this?

like image 351
Vivian River Avatar asked Jul 02 '12 20:07

Vivian River


People also ask

What is XML parser in C?

The Oracle XML parser for C reads an XML document and uses DOM or SAX APIs to provide programmatic access to its content and structure. You can use the parser in validating or nonvalidating mode. This chapter assumes that you are familiar with the following technologies: Document Object Model (DOM).

How do you serialize and deserialize an XML file into AC object?

The code below is similar to the snippet above, and deserializes nested Xml into a complex C# object. Serializer ser = new Serializer(); string path = string. Empty; string xmlInputData = string. Empty; string xmlOutputData = string.

What is a XML parser explain in detail how XML data is parsed with an example?

The XML DOM (Document Object Model) defines the properties and methods for accessing and editing XML. However, before an XML document can be accessed, it must be loaded into an XML DOM object. All modern browsers have a built-in XML parser that can convert text into an XML DOM object.


2 Answers

You can just use XML serialization to create an instance of the class from the XML:

XmlSerializer serializer = new XmlSerializer(typeof(Book));
using (StringReader reader = new StringReader(xmlDocumentText))
{
    Book book = (Book)(serializer.Deserialize(reader));
}
like image 92
Steven Doggart Avatar answered Oct 03 '22 09:10

Steven Doggart


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

Both require that you decorate your class members with attributes that tell the serializer how to operate (different attributes for each).

like image 27
Oded Avatar answered Oct 03 '22 08:10

Oded