2

Is there a way to control/tweak xml declaration while serializing an object using attributes in the class.

In other words I am searching for attribute(s) in C# that can be used to decorate my class and will help in tweaking the xml declaration part(attributes in it) while serializing an object of that class. I know that there is a class XmlDeclaration that can be used to achieve it, however I want to achieve the same result using attributes, which I think is cleaner as different processing instruction stays with the POCO classes and which can be varied across different POCO classes.

Kindly let me know if there is any out-of-the-box feature/custom solution for that or this is just another stupid question... :)

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Sayan Pal
  • 4,768
  • 5
  • 43
  • 82
  • Could you elaborate on what you mean by "*xml declarations*"? I presume by *"(attributes in it)*" you are referring to customizing the attributes written out to the XML itself? – James Jan 15 '14 at 14:48
  • By "xml declarations" I meant the usual first line(if not omitted) in any xml document like the following: . And by attributes I meant attributes in xml declaration and not attributes those are part of xml element(s). – Sayan Pal Jan 15 '14 at 14:49

2 Answers2

1

As your comment notes you are talking about the XML Declaration

<?xml …>

that can start an XML document.

It appears the direct answer is No: there is no XmlDocumentAttribute or something similarly named in the System.Xml.Serialization namespace.

However, there is no need to have the XML serialisation engine write directly to a file. Rather write to an XmlWriter you have correctly configured to write the XML declaration you want (including none). Then pass that writer to the right Serialize method overload.

See this answer for overriding the default encoding in the XML Declaration.

(While this doesn't answer you question—how to do this with attributes in your POCO types—one can argue that the XML Declaration is all about how the XML in the file is encoded so correctly belongs with the file writing/reading code, not the serialisation code.)

Community
  • 1
  • 1
Richard
  • 106,783
  • 21
  • 203
  • 265
0

You would need to override the default XmlWriterSettings and set the OmitXmlDeclaration property to true e.g.

XmlWriterSettings writerSettings = new XmlWriterSettings
{
    OmitXmlDeclaration = true
};
using (StringWriter strWriter = new StringWriter())
using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, writerSettings))
{
    XmlSerializer serializer = new XmlSerializer(typeof(myObject));
    serializer.Serialize(xmlWriter, myObject);
}

Turns out StringWriter defaults to UTF-16, if you need control over the encoding you would need to derive your own StringWriter, there is a good example of how to do that already.

Community
  • 1
  • 1
James
  • 80,725
  • 18
  • 167
  • 237