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

Tho*_*Dev 5 c# xml xml-serialization

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

<Envelope    
xmlns="http://schemas.xmlsoap.org/soap/envelope/" /> 
Run Code Online (Sandbox Code Playgroud)

我希望它看起来像:

<Envelope    
xmlns="http://schemas.xmlsoap.org/soap/envelope/" ></Envelope>`
Run Code Online (Sandbox Code Playgroud)


我写的课是这样的:

[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`
Run Code Online (Sandbox Code Playgroud)

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

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

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

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);
Run Code Online (Sandbox Code Playgroud)

它给了我错误"找不到根元素".

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

Mar*_*iep 11

这里的主要问题是,XmlSerializer来电WriteEndElement()XmlWriter时候会写一个结束标记.但是,<tag/>当没有内容时,这会生成简写形式.分别WriteFullEndElement()写入结束标记.

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

鉴于这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);
Run Code Online (Sandbox Code Playgroud)

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

public XmlTextWriterFull(Stream stream, Encoding enc) : base(stream, enc) { }
public XmlTextWriterFull(String str, Encoding enc) : base(str, enc) { }
Run Code Online (Sandbox Code Playgroud)

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

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);
Run Code Online (Sandbox Code Playgroud)

  • 这取决于消费者的遵守情况.如果生成的XML的使用者不理解速记符号,那么可能需要这样做. (3认同)