Reputation: 811
Here is my code:
[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; }
}
Now after I post these code to the local server which for test:
<xml>
<ToUserName>123</ToUserName>
<FromUserName>45</FromUserName>
<CreateTime>12345678</CreateTime>
<MsgType>text</MsgType>
<Content>greating</Content>
</xml>
Then it will return these:
<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>
Well, as you see. The XML data contains xmlns:xsi and xmlns:xsd which are not allowed in the remote server.
In addition, the remote server is not control by us that I can't change any code or any rules with it.
That means I have to modify the return XML like this:
<xml>
<ToUserName>45</ToUserName>
<FromUserName>123</FromUserName>
<CreateTime>20190921203758</CreateTime>
<MsgType>text</MsgType>
<Content>Hello world</Content>
</xml>
How can I remove the xmlns:xsi and xmlns:xsd when returns the XML? Thank you.
Upvotes: 3
Views: 5964
Reputation: 9642
You can create custom serializer formatter for xml and you can inherit it from default XmlSerializerOutputFormatter
implementation
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);
}
}
Add this formatter in 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()
Upvotes: 15