Skip to content

Instantly share code, notes, and snippets.

@rarous
Created July 20, 2012 12:11
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save rarous/3150395 to your computer and use it in GitHub Desktop.
Save rarous/3150395 to your computer and use it in GitHub Desktop.
Convert XElement to XmlElement
using System.Xml;
using System.Xml.Linq;
public static class XElementExtensions
{
public static XmlElement ToXmlElement(this XElement el)
{
var doc = new XmlDocument();
doc.Load(el.CreateReader());
return doc.DocumentElement;
}
}
@blueboxes
Copy link

Very helpful. You may want to wrap el.CreateReader() in a using statement as it returns an object that implements IDisposable.

@TimothyDJewell
Copy link

TimothyDJewell commented May 3, 2018

Nice; found this while working in a legacy code area. For converting to the middle of an existing XmlDocument instance, you can make this a bit messier like:

public static XmlElement ToXmlElement(this XElement el, XmlDocument ownerDocument)
{
    return (XmlElement)ownerDocument.ReadNode(el.CreateReader());
}

The returned element could then be appended as a child of any element in ownerDocument.

@andreisfedotov
Copy link

๐Ÿ‘ ๐Ÿ‘ ๐Ÿ‘ ๐Ÿ‘ ๐Ÿ‘

@ComSpex
Copy link

ComSpex commented May 5, 2021

Thanks a lot!! It's very helpful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment