How to use XmlWriterSettings() when using override void WriteEndElement()?

前端 未结 5 1659
北恋
北恋 2020-12-11 16:15

I am working with a legacy application that does not import abbreviated empty xml elements. For example:

BAD empty:


G

5条回答
  •  伪装坚强ぢ
    2020-12-11 16:51

    How about this.

    Grab the awesome XmlWrappingWriter class from http://www.tkachenko.com/blog/archives/000585.html (I have omitted the code for the sake of brevity).

    With that, we can create a sub-class as follows (very similar to your original one):

    public class XmlTextWriterFull2 : XmlWrappingWriter
    {
        public XmlTextWriterFull2(XmlWriter baseWriter)
            : base(baseWriter)
        {
        }
    
        public override void WriteEndElement()
        {
            base.WriteFullEndElement();
        }
    }
    

    It can then be invoked like this (again very similar):

    var x_settings = new XmlWriterSettings();
    x_settings.NewLineChars = Environment.NewLine;
    x_settings.NewLineOnAttributes = true;
    x_settings.NewLineHandling = NewLineHandling.None;
    x_settings.CloseOutput = true;
    x_settings.Indent = true;
    x_settings.NewLineOnAttributes = true;
    
    using (XmlWriter writer = XmlWriter.Create(outputFilename, x_settings))
    {
        using (XmlTextWriterFull2 xmlTextWriterFull = new XmlTextWriterFull2(writer))
        {
            var x_serial = new XmlSerializer(typeof(YOUR_OBJECT_TYPE));
            x_serial.Serialize(xmlTextWriterFull, YOUR_OBJECT_INSTANCE);
        }
    }
    

    In my case, an element that had previously been rendered as

    
    
    

    became

    
    

    As you alluded to in your question, this is actually quite a tricky problem due to everything being sealed/internal etc., making overrides rather difficult. I think my biggest problem was trying to get an XmlWriter to accept XmlWriterSettings: beyond this approach, I could find no way of getting the original XmlTextWriterFull to respect the given XmlWriterSettings.

    MSDN states that this method:

    XmlWriter.Create(XmlWriter, XmlWriterSettings)
    

    Can be used to apply the XmlWriterSettings to the XmlWriter. I couldn't get this to work like I wanted (the indentation never worked, for example), and upon decompiling the code, it does not appear that all the settings are used with this particular method, hence why my invocation code just passes in the outputFile (a stream of some sort would work just as well).

提交回复
热议问题