18 Apr 2011 @ 10:00 PM 

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.

Posted By: Boyd
Last Edit: 14 Apr 2011 @ 10:09 PM

EmailPermalink
Tags
Tags: , , ,
Categories: .Net, Programming


 

Responses to this post » (None)

 
Tags
Comment Meta:
RSS Feed for comments

 Last 50 Posts
Change Theme...
  • Users » 3
  • Posts/Pages » 30
  • Comments » 0
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight

GeekPub



    No Child Pages.