I am in the process of developing some code for easily updating my CV, and one of the technologies I am using for this purpose is Linq to XML. As I have said previously on this blog, Linq to XML is an in-memory XML manipulation technology which allows you to manipulate XML as if you would use the XML DOM. So as part of my application I want to use XML because its easy to create or get the structure needed for creating the CV. I have discussed the idea of a CV Builder previously here. So part of this project involves reading XML and reading XML with LINQ to XML seems a rather straight forward process. The first thing you need to know about though is that the IEnumerable interface you need to use exists in the System.Collections.Generic namespace, not System.Collections. If you use only the latter you will get an error message saying:
The non-generic type ‘System.Collections.IEnumerable’ cannot be used with type arguments
Lets show some code that reads XML:
XDocument document = XDocument.Load(context.Server.MapPath(@"CVTemplate.xml"));
XElement root = document.Root;
IEnumerable elements = from el in root.Descendants("parentsection")
select el;
foreach (XElement elem in elements)
{
builder.AppendLine("Element Name:\t" + elem.Name.ToString());
builder.AppendLine("Attributes:");
foreach (XAttribute attrib in elem.Attributes())
{
builder.AppendLine("\t\t" + attrib.Value);
}
foreach (XElement subElem in elem.Descendants())
{
builder.AppendLine("\t\t" + subElem.Name.ToString() + "\n\t\t\t" + subElem.Value);
}
}
context.Response.Write(builder.ToString());
In the code above I use the XDocument class to read the XML from an XML file that I specified in a web.config app setting. I then create an XElement instance by assigning it to the document.Root of the XDocument instance, because its return type is XElement. I then create an enumerable variable elements of type XElement and get the enumerable result from a LINQ query that selects the elements from the XML of the nodes parentsection. I then enumerate through the XElements from the elements variable. Inside the foreach loop I enumerate twice again, once for the attributes of the XML node and the second time for the nested XElements. I just created a StringBuilder instance to write the values as the enumeration took place, its just so that I can see the values and also because I implemented this with a generic handler. Ok so what is next? Well next I need to be able to select items and move them around, but thats for another article.
Place your comment