XmlSerializer Serialize empty variable to use both tags?

后端 未结 3 1554
萌比男神i
萌比男神i 2020-12-10 08:15

I want to be able to load a serialized xml class to a Soap Envelope. I am starting so I am not filling the innards so it appears like:



        
相关标签:
3条回答
  • 2020-12-10 08:18

    The two representations are equiavalent. Why do you need it to appear in the latter form?

    0 讨论(0)
  • 2020-12-10 08:29

    The main issue here is that the XmlSerializer calls WriteEndElement() on the XmlWriter when it would write an end tag. This, however, generates the shorthand <tag/> form when there is no content. The WriteFullEndElement() writes the end tag separately.

    You can inject your own XmlTextWriter into the middle that the serializer would then use to exhibit that functionality.

    Given that serializer is the appropriate XmlSerializer, try this:

    public class XmlTextWriterFull : XmlTextWriter
    {
        public XmlTextWriterFull(TextWriter sink) : base(sink) { }
    
        public override void WriteEndElement()
        {
            base.WriteFullEndElement();
        }
    }
    
    ...
    
    var writer = new XmlTextWriterFull(innerwriter);
    serializer.Serialize(writer, obj);
    

    [Edit] for the case of your added code, add facade constructors for:

    public XmlTextWriterFull(Stream stream, Encoding enc) : base(stream, enc) { }
    public XmlTextWriterFull(String str, Encoding enc) : base(str, enc) { }
    

    Then, use the memory stream as your inner stream in the constructor as before:

    System.IO.MemoryStream memOut = new System.IO.MemoryStream();
    XmlTextWriterFull writer = new XmlTextWriterFull(memOut, Encoding.UTF8Encoding); //Or the encoding of your choice
    xmlout.Serialize(writer, envelope, namespc);
    
    0 讨论(0)
  • 2020-12-10 08:41

    Note for the record: The OP was using the ***Microsoft.***Web.Services.SoapEnvelope class, which is part of the extremely obsolete WSE 1.0 product. This class derived from the XmlDocument class, so it's possible that the same issues would have been seen with XmlDocument.

    Under no circumstances should WSE be used for any new development, and if it is already in use, the code should be migrated as soon as possible. WCF or ASP.NET Web API are the only technologies that should be used for .NET web services going forward.

    0 讨论(0)
提交回复
热议问题