I had a look at string escape into XML and found it very useful.
I would like to do a similar thing: Escape a string to be used in an XML-Attribute.
The string m
public static string XmlEscapeAttribute(string unescaped)
{
if (string.IsNullOrEmpty(unescaped))
return unescaped;
var attributeString = new XAttribute("n", unescaped).ToString();
// Extract the string from the text like: n="text".
return attributeString.Substring(3, attributeString.Length - 4);
}
This solution is similar to the one one proposed by @Mathias E. but it uses LINQ to XML rather than XmlDocument so should be faster.
The SecurityElement.Escape()
solution has a couple of problems. First it doesn't encode new lines so that has to be done as an additional step. Also, it encodes apostrophes as '
which is not correct in an attribute value per the XML spec.
Inspiration for my solution came from this post.