Webiant Logo Webiant Logo
  1. No results found.

    Try your search with a different keyword or use * as a wildcard.

XmlHelper.cs

using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Serialization;

namespace Nop.Core;

/// 
/// XML helper class
/// 
public partial class XmlHelper
{
    #region Methods

    /// 
    /// XML Encode
    /// 
    /// String
    /// 
    /// A task that represents the asynchronous operation
    /// The task result contains the encoded string
    /// 
    public static async Task XmlEncodeAsync(string str)
    {
        if (str == null)
            return null;
        str = Regex.Replace(str, @"[^\u0009\u000A\u000D\u0020-\uD7FF\uE000-\uFFFD]", string.Empty, RegexOptions.Compiled);

        return await XmlEncodeAsIsAsync(str);
    }

    /// 
    /// XML Encode as is
    /// 
    /// String
    /// 
    /// A task that represents the asynchronous operation
    /// The task result contains the encoded string
    /// 
    public static async Task XmlEncodeAsIsAsync(string str)
    {
        if (str == null)
            return null;

        var settings = new XmlWriterSettings
        {
            Async = true,
            ConformanceLevel = ConformanceLevel.Auto
        };

        await using var sw = new StringWriter();
        await using var xwr = XmlWriter.Create(sw, settings);
        await xwr.WriteStringAsync(str);
        await xwr.FlushAsync();

        return sw.ToString();
    }

    /// 
    /// Decodes an attribute
    /// 
    /// Attribute
    /// Decoded attribute
    public static string XmlDecode(string str)
    {
        var sb = new StringBuilder(str);

        var rez = sb.Replace(""", "\"").Replace("'", "'").Replace("<", "<").Replace(">", ">").Replace("&", "&").ToString();

        return rez;
    }

    /// 
    /// Serializes a datetime
    /// 
    /// Datetime
    /// 
    /// A task that represents the asynchronous operation
    /// The task result contains the serialized datetime
    /// 
    public static async Task SerializeDateTimeAsync(DateTime dateTime)
    {
        var xmlS = new XmlSerializer(typeof(DateTime));
        var sb = new StringBuilder();
        await using var sw = new StringWriter(sb);
        xmlS.Serialize(sw, dateTime);

        return sb.ToString();
    }

    #endregion
}