[英]How to change the name of an XML element during XML Serialization runtime (ASP.Net WebApi)
我正在構建對WebAPI服務調用的響應。 默認的XML Serializer最適合我。 我需要生成的是這樣的:
<fooCollection>
<fooMember>
<fooType1>
...bunch of properties for the fooMember
</fooType1>
</fooMember>
<fooMember>
<fooType2>
...bunch of properties for the fooMember
</fooType2>
</fooMember>
</fooCollection
我<fooType>
的問題是<fooType>
元素當前是模型中名為fooType
的對象。 根據我的fooMember
對象的type屬性,響應中的元素名稱需要具有不同的名稱。 這意味着使用[DataContract]
和[DataMember]
屬性之類的名稱為其指定對象名稱以外的名稱似乎不起作用,因為它們只設置了一次,而我找不到在運行時更改它的方法。
我的模型代碼如下所示:
public partial class fooCollection {
private fooCollectionMember[] memberField;
[System.Xml.Serialization.XmlElementAttribute("fooMember")]
public fooCollectionMember[] member { get; set;}
}
public partial class fooCollectionMember {
private fooType fooTypeField;
public fooType fooType { get; set }
}
public partial class fooType {
private object fooProperty;
// ... more properties
public object fooProperty { get; set; }
// ... more properties
}
在運行時/序列化期間,是否可以設置<fooType>
元素的元素名稱?
或者,有沒有一種方法可以重新排列模型,因此fooType
不是內部具有其余屬性的對象,而是fooMember
對象的屬性以及所有其他屬性,而當序列化<fooType>
元素被命名為該屬性的值,並在其中封裝其余屬性?
我最初的服務調用get方法是這樣的:
public FooCollection Get () {
FooCollection foos = new FooCollection();
// code to fill model
return foos;
}
我沒有發現任何東西可以讓我在基於FooCollection中的屬性或對象的響應中采用XML元素,並根據屬性/對象的值在XML響應中更改該元素的名稱。 即,我不能擁有FooProperty
屬性,該屬性的XML響應中生成的元素的每個集合項都具有不同的元素名稱。 換句話說,如果我使用自動返回模型對象和序列化的方法,則此屬性在整個XML文檔中只能具有單個元素名稱。 但是,我找到了一種變通辦法,讓我可以根據需要更改元素名稱。
不是讓我的Get()
服務方法返回FooCollection
類型的對象,而是在返回之后自動對其進行序列化,而是返回HttpResponseMessage
對象。 這樣,我可以手動序列化我的模型,根據需要進行操作,然后將其作為HttpResponseMessage
返回。
因此,現在我的get服務方法可以看起來更像這樣來實現我的目標:
public HttpResponseMessage Get () {
XmlSerializer xmlSerializer = new XmlSerializer(typeof(FooCollection));
System.IO.StringWriter stringWriter = new System.IO.StringWriter();
XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
FooCollection foos = new FooCollection();
// code to populate FooCollection model, assign namespaces, etc
xmlSerializer.Serialize(stringWriter, foos, namespaces);
// Now we can manipulate stringWriter value however is needed to replace the element names
return new HttpResponseMessage() {
Content = new StringContent(stringWriter.ToString(), Encoding.UTF8, "application/xml")
};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.