XmlDocument/XmlElement and the xml:space

Michael Schwarz on Monday, February 16, 2004

When using XML with the Microsoft.XMLDOM ActiveX object I had to put the xml:space attribute to every element where I do not want to remove the blanks at the end of the text. When trying to add an attribute with the name "xml:space" I do not get the result I want. Following short code I have to use to set the xml:space attribute in .NET (C#):

XmlDocument doc = new XmlDocument();

doc.LoadXml("<ROOT/>"); doc.DocumentElement.InnerText = " 1234 ";

XmlAttribute e = doc.CreateAttribute("xml", "space", http://www.w3.org/XML/1998/namespace [1]); e.Value = "preserve";

doc.DocumentElement.Attributes.Append(e);