DataContractSerializer不是爲了讓您控制輸出而設計的。它被設計爲快速,隱含,並且容易爲一個類賦予屬性。
你想要的是XmlSerializer。這使您可以更好地控制XML輸出。
請注意,在我的下面的示例中,我指定了很多可以從屬性名稱中推斷出來的東西,但只是爲了讓您能夠在屬性中覆蓋它們。事實上,我認爲如果所有的屬性都被刪除了,並且一些KnownTypeAttributes被應用了,但我還沒有測試過,那麼這個整個類將會很好地序列化。我不知道這是否會給你所描述的確切的XML(它會在兒童之上創建一個根元素),但希望這可以讓你朝着正確的方向發展。
Attributes That Control XML Serialization
[XmlRoot(Namespace="")]
public class MyClass {
[XmlArray("Children")]
[XmlArrayItem("ConcreteTypeA", typeof(ConcreteTypeA))]
[XmlArrayItem("ConcreteTypeB", typeof(ConcreteTypeB))]
public BaseType[] Children {
get;
set;
}
}
public class BaseType {
}
public class ConcreteTypeA : BaseType {
}
public class ConcreteTypeB : BaseType {
}
編輯:我只是測試它產生的東西非常接近你在尋找的。
void Main()
{
var mc = new MyClass();
mc.Children = new BaseType[] {
new ConcreteTypeA(),
new ConcreteTypeB(),
new ConcreteTypeA(),
new ConcreteTypeB()
};
var serializer = new XmlSerializer(typeof(MyClass));
using (var str = new StringWriter()) {
serializer.Serialize(str, mc);
str.ToString().Dump();
}
}
... ...產生(無用的xmlns從頂部移除)
<MyClass>
<Children>
<ConcreteTypeA />
<ConcreteTypeB />
<ConcreteTypeA />
<ConcreteTypeB />
</Children>
</MyClass>
你應該給你想要的代碼示例.. – Nix 2010-04-10 01:09:50
他做到了,它沒有標明正確。我爲他修好了。 – Josh 2010-04-10 02:57:19