0

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 ?

Deeptechtons
  • 10,945
  • 27
  • 96
  • 178
  • Don't use a StringBuilder to try to build XML in the beginning, use an API like LINQ to XML or XmlWriter. – Martin Honnen Oct 30 '14 at 13:30
  • @MartinHonnen That would be too cumbersone or am i doing it wrong ? since i do `AppendFormat` and the xml goes inside to be replaced by parameters ex; `AppendFormat("",childEntity.Name)` – Deeptechtons Oct 30 '14 at 13:43
  • Yes, you are doing it wrong, if `childEntity.Name` contains an ampersand `&` or a less-than sign `<` or a single quote `'` then your string builder approach would not produce well-formed XML. If you use `new XElement("child", new XAttribute("name", childEntity.Name))` and later save the XElement or the tree you add it to all is right. – Martin Honnen Oct 30 '14 at 15:01
  • @MartinHonnen Got it. Could you put above info in answer so that i can accept ? so `XElement.Parse` expects well formed xml to work without problems then – Deeptechtons Nov 02 '14 at 03:05
  • I have written an answer, based on our exchange in the comments. – Martin Honnen Nov 02 '14 at 09:43

1 Answers1

1

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.

Deeptechtons
  • 10,945
  • 27
  • 96
  • 178
Martin Honnen
  • 160,499
  • 6
  • 90
  • 110