Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize an c# object into xml without schema info? [duplicate]

This is what I did:

A Serializable class:

[Serializable()]
public class Ticket
{
    public string   CitationNumber { get; set; }
    public decimal Amount { get; set; }
}

Then serialize a model into 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();

The output sw.ToString() is like

<?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>  

Is there a way to customize the Serialize() output to remove those schema info like: <?xml version="1.0" encoding="utf-16"?> and xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"?

And how can I change the root element ArrayOfTicket into something else?

Do I have control with those output?

like image 609
Blaise Avatar asked Feb 13 '23 06:02

Blaise


1 Answers

You need a few xml tricks...

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(); 

Output:

<ArrayOfTicket>
  <Ticket>
    <CitationNumber>a</CitationNumber>
    <Amount>1</Amount>
  </Ticket>
  <Ticket>
    <CitationNumber>b</CitationNumber>
    <Amount>2</Amount>
  </Ticket>
</ArrayOfTicket>

PS: I added Indent = true to XmlWriterSettings to get the above output

like image 172
L.B Avatar answered Feb 15 '23 10:02

L.B