15.7. Handling Invalid Characters in an XML String
Problem
You are creating an XML string. Before adding a tag containing a text element, you want to check it to determine whether the string contains any of the following invalid characters:
< > " ' &
If any of these characters are encountered, you want them to be replaced with their escaped form:
< > " ' &
Solution
There are different ways to accomplish this, depending on which XML-creation approach you are using. If you are using XElement, the XCData object, or just adding the text directly as the value of the XElement will take care of the proper escaping. If you are using XmlWriter, the WriteCData, WriteString, WriteAttributeString, WriteValue, and WriteElementString methods take care of this for you. If you are using XmlDocument and XmlElements, the XmlElement.InnerText method will handle these characters.
The two ways to handle this using an XElement work like this. The XCData object will wrap the invalid character text in a CDATA section, as shown in the creation of the InvalidChars1 element in the example that follows. The other method, using XElement, is to assign the text as the value of the XElement, and that will automatically escape the text for you, as shown while creating the InvalidChars2 element:
// set up a string with our invalid chars
string invalidChars = @"<>\&'";
XElement element = new XElement("Root",
new XElement("InvalidChars1",
new XCData(invalidChars)), new XElement("InvalidChars2",invalidChars)); Console.WriteLine("Generated ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access