【发布时间】:2011-03-10 16:24:22
【问题描述】:
所以,我正在尝试为我正在创建的 API 的使用者创建特定的 XML 格式。实际上,您将拥有这样的模型:
public class SampleModel
{
public ErrorCodeEnum ErrorCode { get; set; }
public List<Error> LocalizedErrors { get; set; }
public object AdditionalInformation { get; set; }
}
现在假设我有一个这样的示例模型:
SampleModel model = new SampleModel()
model.ErrorCode = ErrorCodeEnum.InvalidParameters;
model.LocalizedErrors = new List<Error>
{
new Error { For = "SomeField", Message = "Your SomeField value is unacceptable." },
new Error { For = "SomeField2", Message = "Your SomeField2 value is unacceptable." },
};
model.AdditionalInformation = new SomeOtherType { SomeProperty = "Whatever" };
我想确保序列化成这样的:
<xml>
<SampleModel>
<ErrorCode>InvalidParameters</ErrorCode>
<Errors>
<Error For="Somefield">Your SomeField value is unacceptable.</Error>
<Error For="Somefield2">Your SomeField2 value is unacceptable.</Error>
</Errors>
<SomeProperty>Whatever</SomeProperty>
</SampleModel>
我已经解决了相当多的这个问题,但仍然存在一个顽固的问题。基本上,现在,它都像这样序列化:
<xml>
<SampleModel>
<ErrorCode>InvalidParameters</ErrorCode>
<Errors>
<Error For="Somefield">Your SomeField value is unacceptable.</Error>
<Error For="Somefield2">Your SomeField2 value is unacceptable.</Error>
</Errors>
<AdditionalInformation>
<SomeProperty>Whatever</SomeProperty>
</AdditionalInformation>
</SampleModel>
默认 XmlSerializer 在其值的序列化节点周围输出属性名称(在本例中为 AdditionalInformation)。我一直在尝试多种方法来摆脱这个节点。我想看到的基本上是我的值字典,将附加在 XML 根的 1 个子深层,并去掉 AdditionalInformation。所以如果我有这样的模型:
SampleModel model = new SampleModel()
model.ErrorCode = ErrorCodeEnum.InvalidParameters;
model.LocalizedErrors = new List<Error>
{
new Error { For = "SomeField", Message = "Your SomeField value is unacceptable." },
new Error { For = "SomeField2", Message = "Your SomeField2 value is unacceptable." },
};
model.AdditionalInformation = new AThirdType { Foo = "Bar", Bing = "Baz" };
我会得到以下 XML:
<xml>
<SampleModel>
<ErrorCode>InvalidParameters</ErrorCode>
<Errors>
<Error For="Somefield">Your SomeField value is unacceptable.</Error>
<Error For="Somefield2">Your SomeField2 value is unacceptable.</Error>
</Errors>
<Foo>Bar</Foo>
<Bing>Baz</Bing>
</SampleModel>
如果不努力制作我自己的 XmlSerializer / Deserializer,这是否可能?
【问题讨论】:
标签: c# asp.net-mvc api rest xml-serialization