XML Text Writer Document building

Posted on: Thu Oct 23 16:25:40 -0700 2008. Updated on: Thu Oct 23 16:43:36 -0700 2008.
Category: DotNet

Building an XML document object can come in handy often and is a good way to represent data. Here is an example using the XMLTextWriter. This will build a hierarchical xml text representation of some data. At the end we will convert it to an XDocument object, which can be used with LinQ.

// fetch some data
Models.ProductGroups group = _dataContext.GetGroupById(id);
// declare objects
StringWriter sw = new StringWriter();
XmlTextWriter writer = new XmlTextWriter(sw);

writer.WriteStartElement("Product");
writer.WriteAttributeString("Id", group.id.ToString());
writer.WriteElementString("Title", group.Name);

writer.WriteStartElement("Products");
// View All Products
writer.WriteStartElement("Product");
writer.WriteAttributeString("Id", "0");
writer.WriteAttributeString("DisplayOrder", "0");

writer.WriteElementString("Title", "View All");
// close product
writer.WriteEndElement(); 
// close console
writer.WriteEndElement(); 
writer.Close();

// now we will have a string with the xml formatted data in it.
string xml = sw.ToString();

// To convert this xml string to an XDocument do the following
XDocument xmlDoc = XDocument.Parse(xml);

Well, that should give you an idea. You will have to experiment and look at the output xml text to get an idea of how this thing works. Once you convert it to an XDocument object you can do cool things like use LinQ on the object to select specific data.

Comments:

Add a Comment:

simple_captcha.jpg
(human authentication)


Ads

Categories

About

Random foliage

This website is meant to be a reference for ASP Dot Net developers. The entries are a compilation of things I've figured out how to do and that I deem useful to keep of track for future reference. Assumptions: web development with: C Sharp (vb sucks), visual studio 05/08, .net 3.5, meant for programmers. Written by: James Reategui.