XmlHelper可以用于项目中xml操作

XmlHelper.Deserializer<T>(str);//将xml字符串转成对象
XmlHelper.Serializer<T>(obj);//将对象序列化为xml字符串

以asp.net core项目为例,介绍XmlHelper的用法:

  1. 添加xml序列化支持
builder.Services.AddControllers()
    .AddXmlSerializerFormatters();
  1. 接口定义xml入参或出参
[Consumes("application/xml")] //入参是xml 
[Produces("application/xml")] // 返回参数xml
  1. xml示例代码
//webapi接收xml格式的参数
[HttpPost("ticket")]
[Consumes("application/xml")]
public async Task<object> ComponentVierfiyTicket()
{
    using (var reader=new StreamReader(Request.Body))
    {
        var body = await reader.ReadToEndAsync();
        var xmlObj=XmlHelper.Deserializer<ComponentTicket>(body, "xml");//将xml字符串转成对象,示例中根节点是xml
    }
    return "success";
}

//webapi 响应xml格式的数据
[HttpPost("ticket")]
[Produces("application/xml")]
public async Task<object> XmlResponse()
{
    ComponentTicket ticket = new ComponentTicket();
    string t = XmlHelper.Serializer<ComponentTicket>(ticket);//将对象序列化为xml字符串
    return t;
}

xml实体类

[XmlRoot]
public class ComponentTicket
{
    [XmlElement("AppId")]
    public string AppId { get; set; }
    [XmlElement( "CreateTime")]
    public long CreateTime { get; set; }
    [XmlElement( "InfoType")]
    public string InfoType { get; set; }
    [XmlElement( "ComponentVerifyTicket")]
    public string ComponentVerifyTicket { get; set; }
}

xml字符串

<xml>
<AppId>some_appid</AppId>
<CreateTime>1413192605</CreateTime>
<InfoType>component_verify_ticket</InfoType>
<ComponentVerifyTicket>some_verify_ticket</ComponentVerifyTicket>
</xml>