如何在没有模式信息的情况下将c#对象序列化为xml
本文关键字:对象 序列化 xml 情况下 信息 模式 | 更新日期: 2023-09-27 18:17:46
我是这样做的:
可序列化的类:
[Serializable()]
public class Ticket
{
public string CitationNumber { get; set; }
public decimal Amount { get; set; }
}
然后将模型序列化为xml:
var model = cart.Citations
.Select(c => new Ticket(c.Number, c.Amount)).ToList();
var serializer = new XmlSerializer(typeof (List<Ticket>));
var sw = new StringWriter();
serializer.Serialize(sw, model);
return sw.ToString();
输出sw.ToString()
类似于
<?xml version="1.0" encoding="utf-16"?>
<ArrayOfTicket xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Ticket>
<CitationNumber>00092844</CitationNumber>
<Amount>20</Amount>
</Ticket>
</ArrayOfTicket>
是否有一种方法可以自定义Serialize()
输出以删除那些模式信息,如:<?xml version="1.0" encoding="utf-16"?>
和xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
?
我怎么能把根元素ArrayOfTicket
变成别的东西?
我可以控制这些输出吗?
你需要一些xml技巧…
var serializer = new XmlSerializer(typeof(List<Ticket>));
var ns = new XmlSerializerNamespaces();
ns.Add("", "");
var sw = new StringWriter();
var xmlWriter = XmlWriter.Create(sw, new XmlWriterSettings() { OmitXmlDeclaration = true });
serializer.Serialize(xmlWriter, model, ns);
string xml = sw.ToString();
输出:<ArrayOfTicket>
<Ticket>
<CitationNumber>a</CitationNumber>
<Amount>1</Amount>
</Ticket>
<Ticket>
<CitationNumber>b</CitationNumber>
<Amount>2</Amount>
</Ticket>
</ArrayOfTicket>
PS:我将Indent = true
添加到XmlWriterSettings
以获得上述输出