Serialize XML by treating special characters

0

I generate an XML from Nfse, however I need to treat the special characters, eg: ´^~Ç etc, I will serialize it this way:

StringWriter sw = new StringWriter();
XmlTextWriter tw = new XmlTextWriter(sw);
XmlSerializerNamespaces xsn = new XmlSerializerNamespaces();
XmlSerializer ser = new XmlSerializer(typeof(GerarNfseEnvio));
FileStream arquivo = new FileStream("E:\NFSe-" + "RPS" + 
       numero.ToString().PadLeft(15, '0') + 
           ".xml", FileMode.CreateNew);
xsn.Add("", "http://www.abrasf.org.br/nfse.xsd");

ser.Serialize(arquivo, gerar, xsn);
arquivo.Close();

Instead of dealing with field by field, you have some way to change when you create XML , so, do I deal with everything at once?

EDIT

I generate an xml for example with tags, for example

<Discriminacao>Relógio Henry-250\s\nDescrição 62-29\s\n</Discriminacao>

Can not have accents, etc. It should come out this way:

<Discriminacao>Relogio Henry-250\s\nDescricao 62-29\s\n</Discriminacao>

I want to treat the entire xml as there are many fields. This line is when I serialize xml :

ser.Serialize(arquivo, gerar, xsn);

I wanted to know if it is possible before serializing or serializing special characters.

EDIT

I pass the fields this way

gerar.Rps.InfDeclaracaoPrestacaoServico.Tomador.Endereco.Endereco = 
    tomador.EnderecoCobranca.Trim();

But I did not want to put the function in each field, because there are many, I wanted to know if there is any way to do this when generating xml, when serializing or loading it and replacing, something like that.

    
asked by anonymous 07.12.2018 / 19:09

1 answer

1

It may be that this solution is not the fastest, but solves the problem in a satisfactory way, because it is a solution with reflection ( Reflection ):

Create a class that are two extension methods with the following nomenclature and content?

public static class Utils
{
    public static string RemoveAccents(this string s)
    {
        if (string.IsNullOrEmpty(s)) return string.Empty;
        StringBuilder str = new StringBuilder();            
        foreach (char letter in s.Normalize(NormalizationForm.FormD).ToCharArray())
        {
            if (CharUnicodeInfo.GetUnicodeCategory(letter) != 
                UnicodeCategory.NonSpacingMark)
            {
                str.Append(letter);
            }
        }
        return str.ToString();
    }
    public static void NoAccents<T>(this T _class) where T: class
    {
        var _properties = _class.GetType().GetProperties();
        var _fields = _properties.Where(x => x.PropertyType == typeof(string)).ToList();
        foreach (var _field in _fields)
        {
            _field.SetValue(_class, ((string)_field.GetValue(_class)).RemoveAccents());
        }
    }
}

-remover-accents-in-a-string "> example code copied between these responses which is the internal character-removal code with emphasis

where in a given namespace you have access to both methods, one removes only data types string and the other the complex data class , eg:

public class Example
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
}
Example ex = new Example();
ex.Id = 1;
ex.Name = @"Relógio Henry-250\s\nDescrição 62-29\s\n";
ex.Address = "Avenída Souza Líma, 1259";
ex.NoAccents(); // aqui remove os acentos de todas as propriedades do tipo 'string'

Version also for Lists

public static class Utils
{
    public static string RemoveAccents(this string s)
    {
        if (string.IsNullOrEmpty(s)) return string.Empty;
        StringBuilder str = new StringBuilder();            
        foreach (char letter in s.Normalize(NormalizationForm.FormD).ToCharArray())
        {
            if (CharUnicodeInfo.GetUnicodeCategory(letter) != 
                UnicodeCategory.NonSpacingMark)
            {
                str.Append(letter);
            }
        }
        return str.ToString();
    }

    public static void NoAccents<T>(this T _class) where T: class
    {
        void SetValueNoAccents(object valueCurrent)
        {
            var propertiesCurrent = valueCurrent
                    .GetType().GetProperties()
                    .Where(x => x.PropertyType == typeof(string))
                    .ToList();
            foreach (var field in propertiesCurrent)
            {
                field.SetValue(valueCurrent,
                    ((string)field.GetValue(valueCurrent))
                    .RemoveAccents());
            }
        }

        if(_class.GetType().GetInterfaces()
            .Where(t => t.IsGenericType && 
                t.GetGenericTypeDefinition() == typeof(IEnumerable<>)).Any())
        {                
            var _loop = (_class as IEnumerable).GetEnumerator();
            while (_loop.MoveNext())
            {   
                SetValueNoAccents(_loop.Current);
            }
        }
        else
        {                
            SetValueNoAccents(_class);
        }
    }
}

10.12.2018 / 13:57