Here’s a collection of xml extensions I wrote to help make using and navigating xml documents a lot easier.
public static XmlNode FindNode(this XmlDocument doc, string nodeName)
{
if (doc == null)
return null;
XmlNode node = doc.DocumentElement;
return node.FindNode(nodeName);
}
public static XmlNode FindNode(this XmlNode parentNode, string name)
{
if (parentNode == null)
return null;
foreach (XmlNode node in parentNode.ChildNodes)
{
if (node.Name == name)
return node;
XmlNode foundNode = FindNode(node, name);
if (foundNode != null)
return foundNode;
}
return null;
}
FindNode is a method I use a lot when I’m working with 3rd party api’s. It’s a recursive method that traverses the xml document looking for the first node matching the name specified. This way I can ignore a lot of levels of the document to find the property I’m looking for. For example I’ll skip parent objects to get to the children, hold onto the first node and search for a property on it. If I don’t find what I’m looking for I try the next sibling.
/// Reads an xml file and serializes it to the object specified
public static T FromXmlFile<T>(this string path)
{
T result;
using (TextReader textReader = new StreamReader(path))
{
var xmlSerializer = new XmlSerializer(typeof(T));
result = (T)xmlSerializer.Deserialize(textReader);
textReader.Close();
}
return result;
}
//Serializes the class into an xml file that can be retrieved later.
public static void ToXmlFile<T>(this T obj, string path)
{
using (TextWriter textWriter = !File.Exists(path) ? File.CreateText(path) : new StreamWriter(path))
{
var serializer = new XmlSerializer(typeof(T));
serializer.Serialize(textWriter, obj);
textWriter.Close();
}
}
These two methods I will use to store and retrieve a class from an XML file. It’s good for quick and dirty storage.

Categories
Tag Cloud
Blog RSS
Comments RSS
Last 50 Posts
Back
Void « Default
Life
Earth
Wind
Water
Fire
Light 