Snippet – ToXmlDocument and ToXDocument

ToXmlDocument and ToXDocument Extension Class

The other day I found myself working with a XDocument and needed to convert it to a XmlDocument. The best way I found was to make an Extension Class with ToXmlDocument and ToXDocument. Now it is as simple as ToString…

C#


public static class DocumentExtensions
    {
        public static XmlDocument ToXmlDocument(this XDocument xDocument)
        {
            var xmlDocument = new XmlDocument();
            using(var xmlReader = xDocument.CreateReader())
            {
                xmlDocument.Load(xmlReader);
            }
            return xmlDocument;
        }
 
        public static XDocument ToXDocument(this XmlDocument xmlDocument)
        {
            using (var nodeReader = new XmlNodeReader(xmlDocument))
            {
                nodeReader.MoveToContent();
                return XDocument.Load(nodeReader);
            }
        }
    }

VB

Public NotInheritable Class DocumentExtensions
	Private Sub New()
	End Sub
	<System.Runtime.CompilerServices.Extension> _
	Public Shared Function ToXmlDocument(xDocument As XDocument) As XmlDocument
		Dim xmlDocument = New XmlDocument()
		Using xmlReader = xDocument.CreateReader()
			xmlDocument.Load(xmlReader)
		End Using
		Return xmlDocument
	End Function

	<System.Runtime.CompilerServices.Extension> _
	Public Shared Function ToXDocument(xmlDocument As XmlDocument) As XDocument
		Using nodeReader = New XmlNodeReader(xmlDocument)
			nodeReader.MoveToContent()
			Return XDocument.Load(nodeReader)
		End Using
	End Function
End Class
Share This:
Facebooktwitterredditpinterestlinkedintumblr

Jim is a skilled software engineer and author of applications aimed both at home users and various industry markets. Jim's work has been utilized in the public safety, manufacturing, and banking industries. His newest endeavor is aimed at the wine making market. Jim enjoys giving back to the Software Development Community by being active on Stack Overflow. He is also Editor-in-Chief, Author and Developer here at RealWorldDeveloper.com.

Posted in Snippet Tagged with: , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*