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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With