C# Save as XML ASCII characters control characters

Markus Freitag 3,786 Reputation points
2021-09-28T11:39:33.847+00:00

Hello,

<?xml version="1.0" encoding="utf-8"?>  
<root>  
  <EANCode>[)> 06 11V6255595 P605555501 16SV Q2330   </EANCode>  
</root>  

135934--code1.png

ASCII29 ASCII9 and so one.

I want to save special characters inside a XML file.
Works not.

Why and what can I do ?

I know < is special.

Write -->
Read -->

Rename it? Replace it?
What is the best way for this issue? Do you have a sample for me. Write and read.

Thanks.

Best regards

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,367 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,234 questions
{count} votes

Accepted answer
  1. Michael Taylor 47,966 Reputation points
    2021-09-28T15:02:21.487+00:00

    Two approaches come to mind. The first approach is to encode the string value. Base64 is the most common but you could also use hex encoding. Just be sure to always encode/decode so there is no confusion.

    var someValue = "Hello>There";
    var encodedValue = Convert.ToBase64String(Text.Encoding.UTF8.GetBytes(someValue));
    

    The alternative is to wrap the value in a CDATA. CDATA allows you to put non-XML stuff into XML. It is most often used when trying to put things like formatted code into XML. However some characters can still cause issues so personally I would base64 encode the value.

    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 55,601 Reputation points
    2021-09-28T16:29:30.707+00:00

    it pretty simple. you encode special characters as:

    &#<ascii decimal code>;  
    

    for example "<" is

    &#60 ;

    1 person found this answer helpful.
    0 comments No comments

  2. Viorel 112.1K Reputation points
    2021-09-29T08:39:21.073+00:00

    You can also define a convenient format for your needs. For example, you can write the Group Separator as “[GS]” text, etc.:

    <EANCode>[RS]06[GS]11V6255595[GS]P605555501[GS]16SV[GS]Q2330[GS][RS][EOF]</EANCode>
    

    This assumes that “[ ]” does not appear in other places. A simple string.Replace can be used for conversions.

    1 person found this answer helpful.
    0 comments No comments