Serialize XML for special characters

Asked

Viewed 1,087 times

0

I get an Nfse XML, but I need to handle the special characters, example: ´^~Ç etc, I serializo 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 treating field by field, there is some way to change when creating the XML Yeah, I’ll take it all at once?

EDIT

I Gero an xml for example with tags, for example

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

It cannot have accents, Ç etc. It should come out this way:

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

I want to handle the whole xml, because it’s a lot of fields. This line is when I serializo the xml:

ser.Serialize(arquivo, gerar, xsn);

I was wondering if it was possible before serializing, or when serializing, to remove the special characters.

EDIT

I pass the fields this way

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

But I didn’t 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 the xml, when serialize or load it and replace, something like.

  • Make available in your question a copy of the file! an Example can not understand

  • @Virgilionovic I edited to clarify.

  • Mariana needs to generate this data without accentuation and/or special characters, for what reason?

  • When I sign/send XML, it does not accept if it has special characters.

  • On the site itself you can remove this: https://answall.com/questions/2/como-fa%C3%A7o-to-remove-accents-in-a-string look are just a few examples

  • Data comes in a class or list of that class?

  • The data comes from a class, and from a class list, are two types. I’ll take a look.

  • I needed to understand what is really what you have in information

  • @Virgilionovic I Gero an xml, and I need that when passing the data, take the special characters, because if I do by field, by field, it will be a lot of work, because NF-e have several fields, so I wanted to know if you have a way to do this when generating xml.

  • You have to exemplify the data before generating the XML so we can take a north! so it gets complicated I know which is the die, maybe the problem is before and can be solved easier

  • @Virgilionovic I create an xml, passing the data through a schema, to serialize, which would be the xml of Nfse, to generate I inform the value for each field, instead of using replace in each field, I wanted to see if there is any way to do, whether to serialize, when loading xml and replace, there are many fields on a bill, so I wanted to see if there was any way. Was it not clear ? I edited the answer of how I pass the data, to see if it becomes clearer.

  • Mariana, what is the example of the type of data, what is the class, explains all this in the question, is not that it was not clear, is that your question does not explain how you do actually! Put an example of the class, and how you manipulate the data in it

  • It is of a class schema, I put an example in the question, and in the question there was already the form that I create, and serializo the class. Are of type string the data.

  • gerar is the name of the object and the class?

  • You set the generation, but you didn’t set an example of the class! it’s complicated to say if you want to streamline your code by making the class do this character swap for you, always be objective in the questions and clear ...

  • Generate is the name of the object, where I pass the serialized data. The class is huge because it’s the class of an xsd, if you want me to put it in one piece, I can put it, but I don’t think it will solve.

  • Another thing, if you don’t specify a solution I think it’s a duplicate of this: https://answall.com/questions/2/como-fa%C3%A7o-to-remove-accents-in-a-string because it already shows you how to exchange accented characters for accents.

Show 13 more comments

1 answer

1


It may be that this solution is not the fastest, but it solves the problem satisfactorily, 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());
        }
    }
}

Observing: example of code copied between these responses which is the internal character removal code with accentuation

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

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);
        }
    }
}

Reference:

  • I would solve the problem, but I found a more direct way, and less time, I did it as follows: string RemoveAcentos(string palavacomacentos)&#xA; {&#xA; return Encoding.ASCII.GetString(&#xA; Encoding.GetEncoding("Cyrillic").GetBytes(palavacomacentos)&#xA; );&#xA; }

  • @marianac_costa a direct excuse way more this is to disregard the surroundings because I even cited the ways and made a code that solves the problem along with the types of letters exchange with accent to without. A quick way can strand in less code!. If you knew the solution would not have said that.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.