DannyThunder
DannyThunder

Reputation: 1003

How to use the XML Serializer to read xml data from a string?

I'm following this guide (most detailed I've found so far): http://blog.allanglen.com/2009/09/quickly-generate-c-data-objects-from-xml

But at "Step 4: Reading the XML File" I bump into a problem, I dont fetch my XML-data from a file, I get it as a string from a database.

Im new to C# and XML and I cant figure out how to make it work from step 4 with a string!

I'm using:

 XmlDocument doc = new XmlDocument();
                doc.Load(new StringReader(dbString));

Where dbString is the string from the database.

Upvotes: 1

Views: 932

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039498

You could use the LoadXml method:

string xml = ... go and fetch XML from your db
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);

Also note that while XmlDocument is not yet deprecated, XDocument is the preferred way to work with in-memory XML documents starting from .NET 3.5 and higher:

string xml = ... go and fetch XML from your db
XDocument doc = XDocument.Parse(xml);

UPDATE:

Sorry, I haven't actually looked at the blog post you have linked. I was mislead by the code snippet you posted in your question which actually has nothing to do with what's done in step 4 in the aforementioned article and what you are asking about. You seem to be trying to deserialize an XML string into an object. You could use a StringReader for that:

string xml = ... go and fetch XML from your db
XmlSerializer serializer = new XmlSerializer(typeof(catalog));
using (StringReader reader = new StringReader(xml))
{
     catalog catalog = (catalog)serializer.Deserialize(reader);
}

Upvotes: 3

Related Questions