![](/img/trans.png)
[英]How to remove xmlns:xsi and xmlns:xsd from Web API XML serializer
[英]How can I remove xmlns:xsi and xmlns:xsd in the return xml in .net core?
這是我的代碼:
[HttpPost]
[Produces("application/xml")]
public async Task<xml> mp([FromBody]xml XmlData)
{
xml ReturnXmlData = null;
ReturnXmlData = new xml()
{
ToUserName = XmlData.FromUserName,
FromUserName = XmlData.ToUserName,
CreateTime = XmlData.CreateTime,
MsgType = "text",
Content = "Hello world"
};
return ReturnXmlData;
}
[XmlRoot("xml")]
public class xml
{
public string ToUserName { get; set; }
public string FromUserName { get; set; }
public string CreateTime { get; set; }
public string MsgType { get; set; }
public string MsgId { get; set; }
public string Content { get; set; }
}
現在,在我將這些代碼發布到本地服務器后進行測試:
<xml>
<ToUserName>123</ToUserName>
<FromUserName>45</FromUserName>
<CreateTime>12345678</CreateTime>
<MsgType>text</MsgType>
<Content>greating</Content>
</xml>
然后它將返回這些:
<xml xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ToUserName>45</ToUserName>
<FromUserName>123</FromUserName>
<CreateTime>20190921203758</CreateTime>
<MsgType>text</MsgType>
<Content>Hello world</Content>
</xml>
嗯,如你所見。 XML 數據包含遠程服務器中不允許的 xmlns:xsi 和 xmlns:xsd。
另外,遠程服務器不是我們控制的,我不能用它改變任何代碼或任何規則。
這意味着我必須像這樣修改返回 XML:
<xml>
<ToUserName>45</ToUserName>
<FromUserName>123</FromUserName>
<CreateTime>20190921203758</CreateTime>
<MsgType>text</MsgType>
<Content>Hello world</Content>
</xml>
返回 XML 時,如何刪除 xmlns:xsi 和 xmlns:xsd? 謝謝你。
您可以為 xml 創建自定義序列化程序格式化程序,並且可以從默認XmlSerializerOutputFormatter
實現繼承它
public class XmlSerializerOutputFormatterNamespace : XmlSerializerOutputFormatter
{
protected override void Serialize(XmlSerializer xmlSerializer, XmlWriter xmlWriter, object value)
{
//applying "empty" namespace will produce no namespaces
var emptyNamespaces = new XmlSerializerNamespaces();
emptyNamespaces.Add("", "any-non-empty-string");
xmlSerializer.Serialize(xmlWriter, value, emptyNamespaces);
}
}
在Startup
中添加此格式化程序
services
.AddMvc(options =>
{
options.OutputFormatters.Add(new XmlSerializerOutputFormatterNamespace());
})
//there should be one of the following lines in your application already in order to make xml serialization work
//our custom output formatter will override default one since it's iterated earlier in OutputFormatters collection
.AddXmlSerializerFormatters()
//.AddXmlDataContractSerializerFormatters()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.