gpt4 book ai didi

c# 序列化模型到 objectContent

转载 作者:太空宇宙 更新时间:2023-11-03 15:05:46 24 4
gpt4 key购买 nike

我有以下要序列化的类:

public class UpdateDoorCommand : IXmlSerializable
{
// string such as D1
public string DoorId { get; }
public string Name { get; }
public string Notes { get; }

public UpdateDoorCommand(string doorId, string name, string notes)
{
DoorId = doorId;
Name = name;
Notes = notes;
}
public UpdateDoorCommand()
{

}

public XmlSchema GetSchema()
{
throw new NotImplementedException();
}

public void ReadXml(XmlReader reader)
{
throw new NotImplementedException();
}

public void WriteXml(XmlWriter writer)
{
writer.WriteStartElement("Door");
writer.WriteAttributeString("Address", "D1");
writer.WriteElementString("Name", Name);
writer.WriteElementString("Notes", Notes);
writer.WriteEndElement();
}
}

我希望输出看起来像这样:

  <Door Address="D1">
<Name>Name1</Name>
<Notes>Notes1</Notes>
</Door>

我使用以下代码序列化对象:

    [TestMethod]
public async Task XmlSerialisationTest()
{
var model = new UpdateDoorCommand("D1", "Name1", "Notes1");
var mediaTypeFormatters = new MediaTypeFormatterCollection();
mediaTypeFormatters.XmlFormatter.UseXmlSerializer = true;
mediaTypeFormatters.XmlFormatter.WriterSettings.OmitXmlDeclaration = true;
var content = new ObjectContent<UpdateDoorCommand>(model, mediaTypeFormatters.XmlFormatter);
// this does not look like the type
var str = await content.ReadAsStringAsync();
}
}

但是序列化的输出没有给出预期的结果。xml 包装在具有对象类名的元素中。如何使用 ObjectContent 类获得所需的 xml 输出?

请注意,代码需要引用 System.Net.Http.Formatting 才能运行。

最佳答案

我不确定这两种方式是否兼容,但试试这个:

[XmlRoot(ElementName = "Door", DataType = "string")]
public class UpdateDoorCommand : IXmlSerializable
{
// *snip*

public void WriteXml(XmlWriter writer)
{
//writer.WriteStartElement("Door");
writer.WriteAttributeString("Address", "D1");
writer.WriteElementString("Name", Name);
writer.WriteElementString("Notes", Notes);
//writer.WriteEndElement();
}
}

关于c# 序列化模型到 objectContent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43673643/

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