Geeks With Blogs

News

Post Categories

Łukasz Kuryło's blog

In my previous posts I have shown how to get xml data from database and deserialize it. But sometimes we want to work with the xml and do some operations on it. To working with xml, in the .net framework there are two tools for it. One is to use the XmlDocument class and second is the linq to xml with the XDocument class. I personally prefer to work with linq to xml, so I must convert the XmlDocument object to XDocument which I have after I took the xml from database.

 

To convert the XmlDocument to XDocument I have following extension methods

public static class XmlDocumentExtensions
{
    public static XDocument ToXDocument(this XmlDocument document)
    {
        return document.ToXDocument(LoadOptions.None);
    }

    public static XDocument ToXDocument(this XmlDocument document, LoadOptions options)
    {
        using (XmlNodeReader reader = new XmlNodeReader(document))
        {
            return XDocument.Load(reader, options);
        }
    }
}

 

To convert back, that means from XDocument to XmlDocument I have following extension method

        public static XmlDocument ToXmlDocument(this XDocument xDocument)
        {
            var xmlDocument = new XmlDocument();
            using(var xmlReader = xDocument.CreateReader())
            {
                xmlDocument.Load(xmlReader);
            }
            return xmlDocument;
        }
Posted on Wednesday, August 17, 2011 2:15 PM useful snippets | Back to top


Comments on this post: Converting XmlDocument to XDocument and vice versa

Comments are closed.
Comments have been closed on this topic.
Copyright © Łukasz Kuryło | Powered by: GeeksWithBlogs.net