EDIT: you say: "I am concatenating a simple and short XML file and I am not using serialization, so I need to explicitly avoid the XML character manually."
I would strongly advise you not to do this manually. Use the XML API to do all this for you - read in the source files, merge them into one document, but you need to (you probably want to use XmlDocument.ImportNode ) and then write it again. You do not want to write your own XML parsers / formatter. Serialization is somewhat irrelevant here.
If you can give us a short but complete example of what you are trying to do, we can probably help you avoid having to worry about escaping in the first place.
Original answer
It's not entirely clear what you mean, but usually the XML APIs do this for you. You set the text to node and it automatically avoids everything it needs. For example:
LINQ to XML Example:
using System; using System.Xml.Linq; class Test { static void Main() { XElement element = new XElement("tag", "Brackets & stuff <>"); Console.WriteLine(element); } }
DOM example:
using System; using System.Xml; class Test { static void Main() { XmlDocument doc = new XmlDocument(); XmlElement element = doc.CreateElement("tag"); element.InnerText = "Brackets & stuff <>"; Console.WriteLine(element.OuterXml); } }
The result of both examples:
<tag>Brackets & stuff <></tag>
This assumes that you want XML escaping, of course. If you do not, write more detailed information.
Jon Skeet Jul 15 '09 at 16:35 2009-07-15 16:35
source share