C# XmlTextWriter to provide basic formating when writing to StringWriter

In my previous post, I discuss how to write with XmlWriter to a String, that is a workable solution, however, it by default will generate the text formatted.

 

 

It is good to visual, but it does not fit on well when you try to do some unit test on it. 

 

Here is an seque example as how to control the formating like whether or not to indente the output string. remember the formating by XmlTextWriter is really meager/scant/modest.

 

 

 

here is the code:

 

 

[Test]
    public void Test_TextXmlWriter_to_String_Should_be_Valid()
    {

      // this example shows how to write to StringWriter with XmlTextWriter so that we can have 
      // a little control over the Indentation at least 

      using (var sw = new StringWriter())
      {
        using (var textWriter = new XmlTextWriter(sw))
        {
          textWriter.Formatting = Formatting.None;

          textWriter.WriteStartElement("Metrics");
          textWriter.WriteStartElement("Keys");
          textWriter.WriteStartElement("SessionID");
          textWriter.WriteAttributeString("Type", "System.String");
          textWriter.WriteString("{sessionId}");
          textWriter.WriteEndElement();
          textWriter.WriteEndElement();
          textWriter.WriteEndElement();

          textWriter.Flush();

        }

        Assert.AreEqual("<Metrics><Keys><SessionID Type=\"System.String\">{sessionId}</SessionID></Keys></Metrics>", sw.ToString());

      }

    }

 

 

 

Please read here for the article of C# XmlWriter write to String rather than Write to File .

你可能感兴趣的:(C#)