Converting XmlElement To XElement and vice-versa in C#


SUBMITTED BY: Guest

DATE: Nov. 11, 2013, 9:10 p.m.

FORMAT: Text only

SIZE: 2.9 kB

HITS: 1122

  1. Converting XmlElement To XElement and vice-versa in C# [closed]
  2. using System;
  3. using System.Xml;
  4. using System.Xml.Linq;
  5. namespace MyTest
  6. {
  7. internal class Program
  8. {
  9. private static void Main(string[] args)
  10. {
  11. var xmlDocument = new XmlDocument();
  12. xmlDocument.LoadXml("<Root><Child>Test</Child></Root>");
  13. var xDocument = xmlDocument.ToXDocument();
  14. var newXmlDocument = xDocument.ToXmlDocument();
  15. Console.ReadLine();
  16. }
  17. }
  18. public static class DocumentExtensions
  19. {
  20. public static XmlDocument ToXmlDocument(this XDocument xDocument)
  21. {
  22. var xmlDocument = new XmlDocument();
  23. using(var xmlReader = xDocument.CreateReader())
  24. {
  25. xmlDocument.Load(xmlReader);
  26. }
  27. return xmlDocument;
  28. }
  29. public static XDocument ToXDocument(this XmlDocument xmlDocument)
  30. {
  31. using (var nodeReader = new XmlNodeReader(xmlDocument))
  32. {
  33. nodeReader.MoveToContent();
  34. return XDocument.Load(nodeReader);
  35. }
  36. }
  37. }
  38. }
  39. using System.Xml;
  40. using System.Xml.Linq;
  41. #region Extention Method
  42. public static XElement ToXElement(this XmlElement element)
  43. {
  44. return XElement.Parse(element.OuterXml);
  45. }
  46. public static XmlElement ToXmlElement(this XElement element)
  47. {
  48. var doc = new XmlDocument();
  49. doc.LoadXml(element.ToString());
  50. return doc.DocumentElement;
  51. }
  52. #endregion
  53. System.Xml.XmlElement systemXml = (new XElement("nothing")).ToXmlElement();
  54. System.Xml.Linq.XElement linqXml = systemXml.ToXElement();
  55. using System.Xml;
  56. using System.Xml.Linq;
  57. namespace www.dimaka.com
  58. {
  59. internal static class LinqHelper
  60. {
  61. public static XmlDocument ToXmlDocument(this XDocument xDocument)
  62. {
  63. var xmlDocument = new XmlDocument();
  64. using (var reader = xDocument.CreateReader())
  65. {
  66. xmlDocument.Load(reader);
  67. }
  68. var xDeclaration = xDocument.Declaration;
  69. if (xDeclaration != null)
  70. {
  71. var xmlDeclaration = xmlDocument.CreateXmlDeclaration(
  72. xDeclaration.Version,
  73. xDeclaration.Encoding,
  74. xDeclaration.Standalone);
  75. xmlDocument.InsertBefore(xmlDeclaration, xmlDocument.FirstChild);
  76. }
  77. return xmlDocument;
  78. }
  79. }
  80. }
  81. XDocument y = XDocument.Parse(pXmldoc.OuterXml); // where pXmldoc is of type XMLDocument

comments powered by Disqus