XML Text Writer Document building
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.