ServiceStack.Text 是否可以缩进其 xml 输出,因此它不是一长行的 xml?我们想将输出写入一个易于阅读的文本文件。
问问题
524 次
1 回答
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();
}
}
}
于 2013-06-28T13:08:27.630 回答