我在MSDN上找到了这个示例代码,但代码的问题在于它将所有XML写入一行。 我想要缩进和换行符。 我不知道如何在代码中插入XmlWriterSettings。 请帮我这样做。
先谢谢
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
// This is the class that will be serialized.
public class OrderedItem
{
public string ItemName;
public string Description;
public decimal UnitPrice;
public int Quantity;
public decimal LineTotal;
// A custom method used to calculate price per item.
public void Calculate()
{
LineTotal = UnitPrice * Quantity;
}
}
public class Test{
public static void Main()
{
Test t = new Test();
// Write a purchase order.
t.SerializeObject("simple.xml");
}
private void SerializeObject(string filename)
{
Console.WriteLine("Writing With XmlTextWriter");
XmlSerializer serializer =
new XmlSerializer(typeof(OrderedItem));
OrderedItem i = new OrderedItem();
i.ItemName = "Widget";
i.Description = "Regular Widget";
i.Quantity = 10;
i.UnitPrice = (decimal) 2.30;
i.Calculate();
// Create an XmlTextWriter using a FileStream.
Stream fs = new FileStream(filename, FileMode.Create);
XmlWriter writer =
new XmlTextWriter(fs, Encoding.Unicode);
// Serialize using the XmlTextWriter.
serializer.Serialize(writer, i);
writer.Close();
}
}
答案 0 :(得分:0)
我不确定为什么这很重要。不过,我想这一定是你的编辑。默认情况下,XMLSerializer会缩进XML。如果您需要更改任何设置,XmlWriter.Create
方法会出现重载,需要XmlWriterSettings
作为参数。
答案 1 :(得分:0)
您需要在调用XmlWriterSettings
之前在XmlWriter.Create()
课程中设置相应的属性。
另外,我建议进行以下额外更改:
Stream
和XmlWriter
都是disposable,因此应该包含在using
语句中,以防在写入文件时抛出异常。< / p>
为清楚起见,分离出一个通用方法来序列化代码中的任何对象,以计算和编写OrderedItem
类。
因此:
private void SerializeObject(string filename)
{
XmlSerializer serializer = new XmlSerializer(typeof(OrderedItem));
OrderedItem i = new OrderedItem();
i.ItemName = "Widget";
i.Description = "Regular Widget";
i.Quantity = 10;
i.UnitPrice = (decimal)2.30;
i.Calculate();
Console.WriteLine(string.Format("Writing \"{0}\" With XmlTextWriter", filename));
SerializeObject(i, filename);
}
public static void SerializeObject<T>(T obj, string filename)
{
XmlSerializer serializer = new XmlSerializer(obj.GetType());
using (var fs = new FileStream(filename, FileMode.Create))
{
var settings = new XmlWriterSettings() { Indent = true, IndentChars = " ", Encoding = Encoding.Unicode };
using (var writer = XmlWriter.Create(fs, settings))
{
serializer.Serialize(writer, obj);
}
}
}