因此,我試圖爲我創建的API的使用者創建特定的XML格式。實際上,你會像這樣一個模型:複雜的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 /解串器的精力去?
我認爲今天我們將詳細討論這個問題後,我們將在XML序列化方面採取不同的方向;然而,這些建議很有幫助。標記爲已回答。 – Tejs 2011-03-10 20:22:56