ServiceStack.Text是否可以缩进其xml输出,因此它不是xml的一长行?我们希望将输出写入易于阅读的文本文件中。
答案 0 :(得分:2)
您使用的是任何类型的编码吗?因为默认情况下,序列化对象时不会发生任何缩进剥离。请尝试以下代码。
你的xml类对象
public class MyXMLClass
{
[XmlElement]
public string[] Property1 { get; set; }
[XmlElement]
public string[] Property2 { get; set; }
}
序列化方法
static void TestXMLWithIndent()
{
var x = new MyXMLClass()
{
Property1 = new string[] { "TestProp11", "TestProp12", "TestProp13" },
Property2 = new string[] { "TestProp21", "TestProp22", "TestProp23" }
};
var filename = @"c:\temp\testxmlWithIndent.oxi";
using (TextWriter textWriter = new StreamWriter(filename))
{
XmlSerializer serializer = new XmlSerializer(typeof(MyXMLClass));
serializer.Serialize(textWriter, x);
textWriter.Close();
}
}
此代码生成正确的缩进。而下面的代码生成的xml文件没有你提到的缩进。请注意,我使用xmltextwriter时必须使用编码。
static void XmlWithNoIndent()
{
var x = new MyXMLClass()
{
Property1 = new string[] { "TestProp11", "TestProp12", "TestProp13" },
Property2 = new string[] { "TestProp21", "TestProp22", "TestProp23" }
};
var filename = @"c:\temp\testxmlWithNoIndent.oxi";
using (MemoryStream memoryStream = new MemoryStream())
{
using (var xmlTextWriter = new System.Xml.XmlTextWriter(memoryStream, Encoding.Unicode))
{
XmlSerializer xs = new XmlSerializer(typeof(MyXMLClass));
xs.Serialize(xmlTextWriter, x);
MemoryStream memoryBaseStream;
memoryBaseStream = (MemoryStream)xmlTextWriter.BaseStream;
UTF8Encoding encoding = new UTF8Encoding();
File.WriteAllBytes(filename, memoryStream.ToArray());
memoryBaseStream.Dispose();
xmlTextWriter.Close();
memoryStream.Close();
}
}
}