如果 return 格式为 xml,如何删除 Web api 中的架构节点?

How to remove schema node in web api if return format is xml?

我有一个网络 api 方法,该方法将格式作为参数提供 returning xml 和 json.The 数据类型,该方法 return是 DataTable.In json 格式,一切看起来都很好,但在 xml 格式中,数据表的模式和 xml 节点中的一些其他属性也 returning.How 到 return简单 xml 仅包含数据表的数据?此外,我在 WebApiConfig 中使用 QueryStringMapping。

这是 WebApiConfig 代码

public static void Register(HttpConfiguration config)
{
    config.MapHttpAttributeRoutes();
    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{action}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
    config.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("format", "json", new MediaTypeHeaderValue("application/json")));
    config.Formatters.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("format", "xml", new MediaTypeHeaderValue("application/xml")));
    GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
}

这是控制器方法的伪代码

[BasicAuthentication]
[Route("api/{tablename}")]
[HttpGet]
public IHttpActionResult Get(string tablename, string orders = "", int limit = 100)
{
    DataTable dt = new DataTable{TableName="resource"};
    //... Database connection and getting result
    return Ok(new Response{ limit = limit,count=dt.Rows.Count, data =dt });
}

和响应模型

public class Response
{
    public int limit { get; set; }
    public int count { get; set; }
    public DataTable data { get; set; }

}

returned xml的示例

   <Response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <limit>1</limit>
    <count>1</count>
    <data>
    <xs:schema xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" id="NewDataSet">
    <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:MainDataTable="resource" msdata:UseCurrentLocale="true">
    <xs:complexType>
    <xs:choice minOccurs="0" maxOccurs="unbounded">
    <xs:element name="resource">
    <xs:complexType>
    <xs:sequence>
    <xs:element name="ID" type="xs:long" minOccurs="0"/>
    </xs:sequence>
    </xs:complexType>
    </xs:element>
    </xs:choice>
    </xs:complexType>
    </xs:element>
    </xs:schema>
    <diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
    <DocumentElement>
    <resource diffgr:id="resource1" msdata:rowOrder="0">
    <ID>1</ID>
    </resource>
    </DocumentElement>
    </diffgr:diffgram>
    </data>
    </Response>

综上所述,我想return只有数据节点中的资源节点,没有任何属性。

发布这个问题后我找到了答案。问题是数据表对象的 XmlSchema。在覆盖它的 IXmlSerializable 接口的 GetSchema 中编写自定义数据表 xml 序列化程序并返回 null。自定义序列化程序是 there.