如果你願意用XmlRoot來裝飾你的模型,這是一個很好的方法來實現它。假設你有一輛車門。默認的WebAPI配置將返回類似:
<car
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<doors>
<door>
<color>black</color>
</door>
</doors>
</car>
這是你想要什麼:
<car>
<doors>
<door>
<color>black</color>
</door>
</doors>
</car>
這裏的模型:
[XmlRoot("car")]
public class Car
{
[XmlArray("doors"), XmlArrayItem("door")]
public Door[] Doors { get; set; }
}
,你所要做的就是創建一個自定義XmlFormatter如果在XmlRoot屬性中沒有定義名稱空間,則它將具有空的名稱空間。出於某種原因,默認格式化程序總是添加兩個默認名稱空間。
public class CustomNamespaceXmlFormatter : XmlMediaTypeFormatter
{
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content,
TransportContext transportContext)
{
try
{
var xns = new XmlSerializerNamespaces();
foreach (var attribute in type.GetCustomAttributes(true))
{
var xmlRootAttribute = attribute as XmlRootAttribute;
if (xmlRootAttribute != null)
{
xns.Add(string.Empty, xmlRootAttribute.Namespace);
}
}
if (xns.Count == 0)
{
xns.Add(string.Empty, string.Empty);
}
var task = Task.Factory.StartNew(() =>
{
var serializer = new XmlSerializer(type);
serializer.Serialize(writeStream, value, xns);
});
return task;
}
catch (Exception)
{
return base.WriteToStreamAsync(type, value, writeStream, content, transportContext);
}
}
}
最後要做的事情是在WebApiContext中添加新的格式器。一定要刪除(或清除)舊的XmlMediaTypeFormatter
public static class WebApiContext
{
public static void Register(HttpConfiguration config)
{
...
config.Formatters.Clear();
config.Formatters.Add(new CustomNamespaceXmlFormatter{UseXmlSerializer=true});
...
}
}
你可以嘗試這樣的事: HTTP://計算器。com/questions/29352015/how-can-i-create-custom-xml-namespace-attributes-when-consume -a-legacy-soap-se –