Last active
November 12, 2019 18:23
-
-
Save joe-oli/4e36dc54941385cc380fd1ea3dbaa00a to your computer and use it in GitHub Desktop.
XmlElement to XElement and XmlDocument to XDocument
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static XElement ToXElement(this XmlElement xmlelement) | |
{ | |
return XElement.Load(xmlelement.CreateNavigator().ReadSubtree()); | |
} | |
public static XmlDocument ToXmlDocument(this XDocument xdoc) | |
{ | |
var xmldoc = new XmlDocument(); | |
xmldoc.Load(xdoc.CreateReader()); | |
return xmldoc; | |
} | |
//XmlDocument to XDocument | |
XDocument xDoc = XDocument.Load(new XmlNodeReader(xmlDoc)); | |
//To get the root element from the XDocument you use xDoc.Root | |
//here's explicitly a sample to convert XDocument to XElement: | |
XDocument doc = XDocument.Load(...); | |
return doc.Root; | |
//BUT remember this acts on the same reference, i.e. if you edit the resultant XElement, the changes are reflected on XDocument doc as well. This may or may not be desired | |
//Simple conversion from XDocument to XElement | |
XElement cvtXDocumentToXElement(XDocument xDoc) | |
{ | |
XElement xmlOut = XElement.Parse(xDoc.ToString()); | |
return xmlOut; | |
} | |
//BUT remember, this creates a completely new instance of XElement, i.e. changes made to XElement wont be reflected on XDocument. This may or may not be desired | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment