如何在没有架构信息的情况下将c#对象序列化为xml?

时间:2014-08-12 20:51:45

标签: c# xml serialization

这就是我所做的:

Serializable类:

[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更改为其他内容?

我可以控制这些输出吗?

1 个答案:

答案 0 :(得分:5)

你需要一些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以获取上述输出