.net core api 实现解析xml 参数

------------------------------------------------------------------拓展第三方接口xml 传参,返回参-----------------------------------------

1.在 startup.cs 中增加增加解析xml格式

services.AddXmlSerializerFormatters();

2.定义接口,根据要求 第三方接口

增加特性 context-type  

[Consumes("application/xml")] //入参是xml 
[Produces("application/xml")] // 返回参数xml

3.定义接口参数实体定义

[DataContract(Name = "LIST" )] 
[XmlRoot]
 public class LIST
    {
        [DataMember(Name = "1")]
        public string 1{ get; set; }

        [DataMember(Name = "2")]
        public string 2{ get; set; }
         
        [DataMember(Name = "3")]
        public dynamic 3{ get; set; }  //--指定动态参数 业务需要
    }

4.根据xmlnode集合构造 xml 

XmlDocument xmldoc = new XmlDocument();
            XmlDeclaration dec = xmldoc.CreateXmlDeclaration("1.0", "utf-8", null);
            xmldoc.AppendChild(dec);

            XmlElement test= xmldoc.CreateElement(p_type);
            xmldoc.AppendChild(test);
              
            foreach (var item in xmlNodes)
            { 
                var t = xmldoc.CreateElement(item.Name);
                t.InnerText = item.InnerText;
                test.AppendChild(t);
            }

            MemoryStream stream = new MemoryStream();
            var writer = new XmlTextWriter(stream, null);
            writer.Formatting = Formatting.Indented;
            xmldoc.Save(writer);
            StreamReader streamReader = new StreamReader(stream, Encoding.UTF8);
            stream.Position = 0;
            string xmlstring = streamReader.ReadToEnd();
            streamReader.Close();
            stream.Close();
            return xmlstring;

 

posted @ 2022-04-07 14:35  begin_end  阅读(859)  评论(0)    收藏  举报