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#中的XmlTextWriter将XML数据写入到字符串中,并控制输出格式,避免默认的格式化操作。通过设置Formatting属性为None,可以生成未格式化的XML字符串,这对于单元测试等场景非常有用。
3134

被折叠的 条评论
为什么被折叠?



