Search code examples
linq-to-xmlxelement

Does XElement.Parse escape special characters


Assume i got code below, where

            xmlElement.AddAfterSelf(XElement.Parse(sbXml.ToString()));
  • xmlElement : and XElement that contains a parent tag

  • sbXml : StringBuilder with the xml string something like this <Child name='Hi'></Child> (unescaped of special charcters or xml entities, but a valid xml)

Does the XElement.Parse ensure to properly encode the special characters so that when i do XDocument.Save i don't hit with exception's ?


Solution

  • XDocument.Load/Parse as well as XElement.Load/Parse use an XML parser (which in the .NET framework is a concrete subclass of XmlReader) and of course that way it expects well-formed XML as the input. Using string concatenation to construct XML is not the right approach in the .NET framework as there are classes like XmlWriter and of course the tree based LINQ to XML or the DOM implementation which allow you to construct XML and ensure that any saved, serialized representation is well-formed XML (or you get an error indicating the problem when constructing and serializing the tree). So don't use string concatenation, instead build your XML with XmlWriter or with LINQ to XML, as for example with new XElement("child", new XAttribute("name", childEntity.Name)). That way, if childEntity.Name contains some characters (like < or &) that need to be escaped, the Save or ToString methods take care of that.