Saturday, February 12, 2011

Preserve white space in string with XmlTextWriter.WriteString

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?

  • 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();
        }
    }
    
  • 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.

0 comments:

Post a Comment