A pedant that hangs out in the dark corner-cases of the web.

Monday, February 01, 2010

Converting between XDocument and XmlDocument, XElement and XmlElement

Here's a class to provide extension methods for conversion between System.Xml and System.Xml.Linq classes:

using System.Xml;
using System.Xml.Linq;

/// <summary>
/// Provides extension methods for simple conversion between System.Xml and System.Xml.Linq classes.
/// </summary>
public static class XmlLinqConversionExtensions
{
  /// <summary>
  /// Converts an XDocument to an XmlDocument.
  /// </summary>
  /// <param name="xdoc">The XDocument to convert.</param>
  /// <returns>The equivalent XmlDocument.</returns>
  public static XmlDocument ToXmlDocument(this XDocument xdoc)
  {
    var xmldoc = new XmlDocument();
    xmldoc.Load(xdoc.CreateReader());
    return xmldoc;
  }
  
  /// <summary>
  /// Converts an XmlDocument to an XDocument.
  /// </summary>
  /// <param name="xmldoc">The XmlDocument to convert.</param>
  /// <returns>The equivalent XDocument.</returns>
  public static XDocument ToXDocument(this XmlDocument xmldoc)
  {
    return XDocument.Load(xmldoc.CreateNavigator().ReadSubtree());
  }
  
  /// <summary>
  /// Converts an XElement to an XmlElement.
  /// </summary>
  /// <param name="xelement">The XElement to convert.</param>
  /// <returns>The equivalent XmlElement.</returns>
  public static XmlElement ToXmlElement(this XElement xelement)
  {
    return new XmlDocument().ReadNode(xelement.CreateReader()) as XmlElement;
  }
  
  /// <summary>
  /// Converts an XmlElement to an XElement.
  /// </summary>
  /// <param name="xmlelement">The XmlElement to convert.</param>
  /// <returns>The equivalent XElement.</returns>
  public static XElement ToXElement(this XmlElement xmlelement)
  {
    return XElement.Load(xmlelement.CreateNavigator().ReadSubtree());
  }
}

5 comments:

Bebel said...

Thank You Very much for your function ToXelement. I've been searching it for two 2 days.
Thanks a lot!

Anonymous said...

CreateReader creates a reader, that implements IDisposable. So you should use:

using (...CreateReader(...)) {
...
}

otherwise memory leaks will occur.

Extra Makots said...
This comment has been removed by the author.
Anonymous said...

Thanks for your class, very handy :)

Serge SB said...

For some strange reason, sometimes ToXmlElement(this XElement xelement) doesn't work (I think, it is somehow connected with user permissions).

So, I used this method instead to convert XElement to XmlElement:

var xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xElement.ToString());
var xmlElement = xmlDoc.DocumentElement;