XmlSerializer序列化空变量以使用两个标签?

我希望能够将序列化的xml类加载到Soap Envelope。 我开始所以我不填充内脏所以它看起来像:

 

我希望它看起来像:

 ` 

我写的课是这样的:

 [System.SerializableAttribute()] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.xmlsoap.org/soap/envelope/")] [System.Xml.Serialization.XmlRootAttribute(Namespace = "http://schemas.xmlsoap.org/soap/envelope/",ElementName="Envelope", IsNullable = true)] public class TestXmlEnvelope { [System.Xml.Serialization.XmlElement(ElementName="Body", Namespace="http://schemas.xmlsoap.org/soap/envelope/")] public System.Collections.ArrayList Body = new System.Collections.ArrayList(); } //class TestXmlEnvelope` 

我使用它作为一个例子,因为其他人可能想要它在一个单独的元素中。 我相信这一定很简单,但遗憾的是我不知道正确的关键字。

一如既往地感谢您的帮助。

[编辑]当我尝试使用此指令时出现错误

 System.Xml.Serialization.XmlSerializer xmlout = new System.Xml.Serialization.XmlSerializer(typeof(TestXmlEnvelope)); System.IO.MemoryStream memOut = new System.IO.MemoryStream(); xmlout.Serialize(memOut, envelope, namespc); Microsoft.Web.Services.SoapEnvelope soapEnv = new Microsoft.Web.Services.SoapEnvelope(); soapEnv.Load(memOut); 

它给我错误“未找到根元素”。

[编辑]我修正了错误,问题是在我序列化对象之后我没有设置memOut.Position = 0.我仍然希望这个问题可以帮助其他可能想要这样做的人。

这里的主要问题是XmlSerializer在写入结束标记时会调用XmlWriter上的WriteEndElement() 。 但是,当没有内容时,这会生成速记表单。 WriteFullEndElement()写入结束标记。

您可以将自己的XmlTextWriter注入到序列化程序随后用于展示该function的中间。

鉴于serializer是适当的XmlSerializer ,请尝试以下方法:

 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); 

[编辑]对于添加代码的情况,添加外观构造函数:

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

然后,像以前一样在构造函数中使用内存流作为内部流:

 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); 

记录的注意事项:OP使用的是***。***。Web.Services.SoapEnvelope类,它是极其过时的WSE 1.0产品的一部分。 此类派生自XmlDocument类,因此XmlDocument可能会出现相同的问题。

在任何情况下都不应将WSE用于任何新开发,如果它已经在使用中,则应尽快迁移代码。 WCF或ASP.NET Web API是唯一应该用于.NET Web服务的技术。

这两种表述是等价的。 为什么你需要它以后一种forms出现?