How can i easily sanitize the values I pass into the Value property of an XAttribute.
Asked
Active
Viewed 1,076 times
1
-
1Define "sanitize" and you might get a useful answer. – spender Jul 08 '10 at 23:31
-
Well basically its throwing an error on save that it cant accept a certain character, '/0'. I assume there are other chars it cannot accept, so i was wondering if there is a method to remove them all. – Dested Jul 08 '10 at 23:32
-
1maybe add that info to the actual question... – Rex M Jul 08 '10 at 23:44
2 Answers
1
Here's an extension method to clean away your trouble. /0 is not allowed in XML. I'm not sure if other chars are also disallowed, but I believe not. Probably best to start at ' '
.
void Main()
{
Console.WriteLine("123\0394".XmlSanitize());
}
public static class XmlHelpers
{
public static string XmlSanitize(this string badString)
{
return new String(badString.Where(c => c >=' ').ToArray());
}
}

spender
- 117,338
- 33
- 229
- 351
1
You could try:
string value = "!@#$%^&*()123%^&*(!@#\(*!&10987"
value = System.Security.SecurityElement.Escape(value);
This will escape characters that are invalid as XML attribute values.

Sean Amos
- 2,260
- 19
- 13