XMLExtensions.cs 1.1 KB

12345678910111213141516171819202122232425262728293031323334
  1. using System.IO;
  2. using System.Text;
  3. using System.Xml;
  4. namespace InABox.Core
  5. {
  6. public static class XmlHelperExtentions
  7. {
  8. /// <summary>
  9. /// Loads a string through .Load() instead of .LoadXml()
  10. /// This prevents character encoding problems.
  11. /// </summary>
  12. /// <param name="xmlDocument"></param>
  13. /// <param name="xmlString"></param>
  14. /// <param name="encoding"></param>
  15. public static void LoadString(this XmlDocument xmlDocument, string xmlString, Encoding encoding = null)
  16. {
  17. if (encoding == null) encoding = Encoding.UTF8;
  18. // Encode the XML string in a byte array
  19. var encodedString = encoding.GetBytes(xmlString);
  20. // Put the byte array into a stream and rewind it to the beginning
  21. using (var ms = new MemoryStream(encodedString))
  22. {
  23. ms.Flush();
  24. ms.Position = 0;
  25. // Build the XmlDocument from the MemorySteam of UTF-8 encoded bytes
  26. xmlDocument.Load(ms);
  27. }
  28. }
  29. }
  30. }