C# XmlTextWriter to provide basic formating when writing to StringWriter

本文介绍如何使用C#中的XmlTextWriter将XML数据写入到字符串中,并控制输出格式,避免默认的格式化操作。通过设置Formatting属性为None,可以生成未格式化的XML字符串,这对于单元测试等场景非常有用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 .

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值