NanoXLSX.Core 3.2.1
Loading...
Searching...
No Matches
XmlUtils.cs
1/*
2 * NanoXLSX is a small .NET library to generate and read XLSX (Microsoft Excel 2007 or newer) files in an easy and native way
3 * Copyright Raphael Stoeckli © 2026
4 * This library is licensed under the MIT License.
5 * You find a copy of the license in project folder or on: http://opensource.org/licenses/MIT
6 */
7
8using System.Collections.Generic;
9using System.Text;
10
11namespace NanoXLSX.Utils.Xml
12{
13 // TODO Set to internal in next major release
18 public static class XmlUtils
19 {
26 public static string SanitizeXmlValue(string input)
27 {
28 if (input == null) { return ""; }
29 var len = input.Length;
30 var illegalCharacters = new List<int>(len);
31 int i;
32 for (i = 0; i < len; i++)
33 {
34 if (char.IsSurrogate(input[i]))
35 {
36 if (i + 1 < input.Length && char.IsSurrogatePair(input[i], input[i + 1]))
37 {
38 // Valid surrogate pair; append both characters as-is.
39 i++; // Skip the next character.
40 continue;
41 }
42 else
43 {
44 illegalCharacters.Add(i);
45 continue;
46 }
47 }
48 if (input[i] < 0x9 || input[i] > 0xA && input[i] < 0xD || input[i] > 0xD && input[i] < 0x20 || input[i] > 0xD7FF && input[i] < 0xE000 || input[i] > 0xFFFD)
49 {
50 illegalCharacters.Add(i);
51 continue;
52 } // Note: XML specs allow characters up to 0x10FFFF. However, the C# char range is only up to 0xFFFF; Higher values are neglected here
53 }
54 if (illegalCharacters.Count == 0)
55 {
56 return input;
57 }
58
59 var sb = new StringBuilder(len);
60 var lastIndex = 0;
61 len = illegalCharacters.Count;
62 for (i = 0; i < len; i++)
63 {
64 sb.Append(input.Substring(lastIndex, illegalCharacters[i] - lastIndex));
65 sb.Append(' '); // Whitespace as fall back on illegal character
66 lastIndex = illegalCharacters[i] + 1;
67 }
68 sb.Append(input.Substring(lastIndex));
69 return sb.ToString();
70 }
71 }
72}
Class providing static methods to manipulate XML during packing or unpacking.
Definition XmlUtils.cs:19
static string SanitizeXmlValue(string input)
Method to sanitize XML string values between two XML tags or in an attribute. Not considered are '<',...
Definition XmlUtils.cs:26