简体   繁体   English

如何在从XmlObjectSerializer派生的类中设置XmlWriterSettings的缩进量?

[英]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. 我正在扩展XmlObjectSerializer ,我想配置它的缩进,但是它在XmlWriterSettings成员内部,并且是只读的。 From the documentation i can see that it can be set only when creating an XmlWriter instance like: 从文档中,我可以看到只有在创建XmlWriter实例时才可以设置它:

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

But i don't create one. 但是我不创造一个。 I create my class XmlObjectWithRefSerializer , derived from XmlObjectSerializer , like this: 创建我的类XmlObjectWithRefSerializer ,源自XmlObjectSerializer ,就像这样:

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: 在我的类中,它在我必须重写的方法中用作XmlDictionaryWriter

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. Settings属性(类型XmlWriterSettings )于抽象XmlWriter类被定义为虚拟的,所以可以覆盖在子类中,但是这不会在您的方案帮助。

You are calling the WriteObject method, passing the stream to write to. 您正在调用WriteObject方法,并传递要写入的流。 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). 接下来发生的是,在XmlObjectSerializer类中,该方法将创建一个新的XmlDictionaryWriter (它只是提供的流的包装),然后将其传递给您重写的方法( WriteObjectContent等)。

It would appear that at no point is there a hook you can use to replace the writer settings with your own. 似乎根本没有一个钩子可用于用您自己的编写器设置替换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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