说我有以下课程:
public class Test
{
public string FullName { get; set; }
public int Score { get; set; }
public DateTime StartDate { get; set; }
}
然后我创建一个实例:
Test t = new Test
{
FullName = "Bob Smith",
Score = 3.4,
StartDate = DateTime.Now
};
我使用XmlSerializer将类转换为XML
using (var textWriter = new StringWriter())
{
using (XmlWriter xmlWriter = XmlWriter.Create(textWriter))
{
var serializer = new XmlSerializer(typeof(Test), CreateOverrides());
serializer.Serialize(xmlWriter, t);
}
xml = textWriter.ToString();
}
所以我最终得到了这个:
<Test>
<FullName>Bob Smith</FullName>
<Score>3.4</Score>
<StartDate>2018-03-12T13:24:19.9284562+00:00</StartDate>
</Test>
如果使用某种覆盖我想做什么,所以我可以格式化XML。所以我想说我希望看到以下输出:
<Test>
<FullName>First Name: Bob. Surname: Smith</FullName>
<Score>3.4000</Score>
<StartDate>2018 (this year) 03 (Spring) 12 (middle period)</StartDate>
</Test>
如果有任何方法我可以根据类型格式化或更改XML输出通过将某些内容传递给序列化程序,Date,Int等。我一直在看XmlAttributeOverrides,但我似乎无法改变内容。
private static XmlAttributeOverrides CreateOverrides()
{
//Do something here to change the content...
//if int then change the format to 4 decimal places
//if date then change the date into a custom format
//etc
}
我需要通过序列化程序执行此操作。我不想修改现有的Test类,使用属性来忽略和替换xml元素。
我正在尝试做什么?