Preserve white space in string with XmlTextWriter.WriteString
-
03-07-2019 - |
Question
I am writing an XML document in C#.
I have something like this...
string output = "REAPP DUE NO OF M CASE NBR APPL NBR DATE GRPS M CASE NBR APPL NBR DATE GRPS _ _ _";
and I do this...
objXmlTextWriter.WriteStartElement("Case");
objXmlTextWriter.WriteString(record);
objXmlTextWriter.WriteEndElement();
and the xml element turns out like this...
<Case>REAPP DUE NO OF REAPP DUE NO OF M CASE NBR APPL NBR DATE GRPS M CASE NBR APPL NBR DATE GRPS _ _ _ </Case>
It has basically converted white space with length greater than 1 to 1 character of white space.
How do I prevent this?
Solution
Sorry, got confused before (deleted the wrong answer). But I can't reproduce what you seem to be seeing. Check this program... it does preserve spaces.
class Program
{
static void Main(string[] args)
{
XmlWriter w = XmlTextWriter.Create("./foo.xml");
w.WriteStartElement("foo");
w.WriteString(" THIS HAS VARYING SPACeS ");
w.WriteEndElement();
w.Close();
StreamReader sr = new StreamReader("./foo.xml");
Console.WriteLine(sr.ReadToEnd());
Console.ReadKey();
}
}
OTHER TIPS
OK...
This is only an IE display problem. Something to do with the font I guess.
When I open the XML in notepad++ I see the white space is actually preserved properly.
Instead of WriteString() you could use WriteCData() to enclose the text in a CDATA block if display in IE is important.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow