简体   繁体   中英

How to set the indent of XmlWriterSettings in a class, derived from XmlObjectSerializer?

I am extending XmlObjectSerializer and i would like to configure the indent of it, but it is inside the XmlWriterSettings member and that is read only. From the documentation i can see that it can be set only when creating an XmlWriter instance like:

XmlWriter writer = XmlWriter.Create(stringWriter, settings);

But i don't create one. I create my class XmlObjectWithRefSerializer , derived from XmlObjectSerializer , like this:

StreamWriter swWriter = File.CreateText(sFilename);
var serializer = new XmlObjectWithRefSerializer(tType);
serializer.WriteObject(swWriter.BaseStream, oData);
swWriter.Close();

Inside my class, it is used as XmlDictionaryWriter in methods i have to override like:

public override void WriteObjectContent(XmlDictionaryWriter writer, object graph)
{
    XmlWriterSettings settings = new XmlWriterSettings();
    settings.OmitXmlDeclaration = true;
    settings.Indent = true;
    //writer.Settings = settings;  --> Fails because read only
    ...
}

So, is there a way to give settings to my derived class?

In short, I don't think you can.

The Settings property (of type XmlWriterSettings ) on the abstract XmlWriter class is defined as virtual, so can be overridden in subclasses, however this would not help in your scenario.

You are calling the WriteObject method, passing the stream to write to. What happens next is that, in the XmlObjectSerializer class, the method will create a new XmlDictionaryWriter (which is just a wrapper around the supplied stream) that then gets passed to the methods that you override ( WriteObjectContent et al).

It would appear that at no point is there a hook you can use to replace the writer settings with your own.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM