gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 01:54:18 25 4
gpt4 key购买 nike

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

<Envelope    
xmlns="http://schemas.xmlsoap.org/soap/envelope/" />

我希望它看起来像:

<Envelope    
xmlns="http://schemas.xmlsoap.org/soap/envelope/" ></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电话 WriteEndElement()XmlWriter 上什么时候写结束标签。但是,这会生成简写 <tag/>没有内容时的形式。 WriteFullEndElement()单独写结束标签。

你可以注入(inject)你自己的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);

[编辑] 对于您添加的代码,为以下内容添加外观构造函数:

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

关于c# - XmlSerializer 序列化空变量以使用两个标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/254821/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com