• C# 运用反射把实体类反射成你所想要的格式


    下面是要转换成的Xml格式

    <?xml version="1.0" encoding="UTF-8" ?>
    <NDEML  templateVersion="1.0" >
        <header>
            <!-- 导出时间 -->
            <exportDate>2014-10-10 22:23:34</exportDate>
            <!--  数据业务类型 -->
            <dataType> N707</dataType>
        <!--数据来源-->
        <sourceCode ref="210000">辽宁省级平台</sourceCode>
            <!--数据目标-->
            <targetCode ref="00">国家平台</targetCode>
            <!--数据来源类型-->
            <sourceType ref="1">省平台上传</sourceType>
        </header>
        <body>        
            <bodyItem itemId="1101">            
                <data>
                  <N707>
                    < N707-01></ N707-01>
                    ……
                  </N707>
                  <N707>
                    ……
                  </N707>
                </data>
                <!--数据信息扩展,保留-->
                <extendData/>
            </bodyItem>
            <bodyItem itemId="1102">
                <data>
                  <N707>
                    < N707-01></ N707-01>
                    ……
                  </N707>
                  <N707>
                    ……
                  </N707>
                    ……
                </data>
                <!--数据信息扩展,保留-->
                <extendData/>
            </bodyItem>
        </body>
    </NDEML>

    我用的是C#的控制台程序写的,需要创建类,然后通过反射,递归让他实现拼装,后期要加(减)什么字段改变什么类型直接更改实体类就行了下面是C#代码

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.Text;
    
    namespace EntityXml
    {
        class Program
        {
            static void Main(string[] args)
            {
                //实例化StringBuilder
                var xml = new StringBuilder();
                //往StringBuilder添加
                xml.AppendLine("<?xml version="1.0" encoding="UTF-8"?>");
                //实例化明细类
                var details = new UploadDetail();
    
                details.Head = new Head() { SourceCode = new SourceCode("辽字省平台") };
    
                details.Body = new Body();
    
    
                var bodyItem = new BodyItem();
                bodyItem.ItemId = "10000";
                bodyItem.Data = new Data();
                var detail1 = new Detail { N707_01 = "n707-01 1", N707_02 = "n707-02 1" };
                bodyItem.Data.Details.Add(detail1);
                var detail2 = new Detail { N707_01 = "n707-01 2", N707_02 = "n707-02 2" };
                bodyItem.Data.Details.Add(detail2);
    
                details.Body.BodyItems.Add(bodyItem);
    
                xml.AppendLine(ToXml(details, false));
                Console.WriteLine(xml.ToString());
            }
    
            public static string ToXml(Entity entity, bool isValue)
            {
                var xml = new StringBuilder();
                var type = entity.GetType();
                var atts = type.GetCustomAttributes(false);
                var nodeName = "";  
                foreach (var att in atts)
                {
                    if (att is XmlNameAttribute)
                    {
                        var attr = att as XmlNameAttribute;
                        nodeName = attr.XmlName;
                    }
                }
                var pros = new List<PropertyInfo>();
                xml.Append($"<{nodeName}");
                foreach (var pro in type.GetProperties())
                {
                    var proAtts = pro.GetCustomAttributes(false);
                    var isXmlProperty = false;
                    foreach (var att in proAtts)
                    {
                        //xml节点属性的属性
                        if (att is IsXmlPropertyAttribute)
                        {
                            isXmlProperty = true;
                            var attr = att as IsXmlPropertyAttribute;
                            if (attr.IsXmlProperty == true)
                            {
                                var IsXmlNameMark = false;
                                foreach (var nameAtt in proAtts)
                                {
                                    if (nameAtt is XmlNameAttribute)
                                    {
                                        var nameAttr = nameAtt as XmlNameAttribute;
                                        xml.Append($" {nameAttr.XmlName}="{pro.GetValue(entity, null).ToString()}"");
                                        IsXmlNameMark = true;
                                    }
                                }
                                if (!IsXmlNameMark)
                                {
                                    xml.Append($" {pro.Name}="{pro.GetValue(entity, null).ToString()}"");
                                }
                            }
                        }
                    }
                    //节点属性
                    if (!isXmlProperty)
                    {
                        pros.Add(pro);
                    }
                }
                xml.AppendLine($">");
    
                if (isValue)
                {
                    xml.AppendLine($"{type.GetProperty("SelfValue", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(entity, null)}");
                }
                else
                {
                    foreach (var pro in pros)
                    {
                        var proAtts = pro.GetCustomAttributes(false);
                        if (pro.PropertyType.IsSubclassOf(typeof(Entity)))
                        {
                            var childEntity = pro.GetValue(entity, null) as Entity;
    
                            var isXmlValueMark = false;
                            foreach (var att in proAtts)
                            {
                                if (att is IsXmlValueAttribute)
                                {
                                    isXmlValueMark = true;
                                    xml.AppendLine(ToXml(childEntity, true));
                                    break;
                                }
                            }
                            if (!isXmlValueMark)
                            {
                                xml.AppendLine(ToXml(childEntity, false));
                            }
                        }
                        else
                        {
                            if (pro.PropertyType.IsGenericType)
                            {
                                var list = pro.GetValue(entity, null) as IList;
                                foreach (var item in list)
                                {
                                    xml.AppendLine(ToXml(item as Entity, false));
                                }
                            }
                            else
                            {
                                var IsXmlNameMark = false;
                                foreach (var att in proAtts)
                                {
                                    IsXmlNameMark = true;
                                    if (att is XmlNameAttribute)
                                    {
                                        var attr = att as XmlNameAttribute;
                                        xml.AppendLine($"<{attr.XmlName}>{pro.GetValue(entity, null)}</{attr.XmlName}>");
                                    }
                                }
                                if (!IsXmlNameMark)
                                {
                                    if (pro.PropertyType.Name == "DateTime")
                                    {
                                        if (pro.GetValue(entity, null) == null)
                                        {
                                            xml.AppendLine($"<{pro.Name}></{pro.Name}>");
                                        }
                                        else
                                        {
                                            xml.AppendLine($"<{pro.Name}>{Convert.ToDateTime(pro.GetValue(entity, null)).ToString("yyyy-MM-dd HH:mm:ss")}</{pro.Name}>");
                                        }
                                    }
                                    else
                                    {
                                        xml.AppendLine($"<{pro.Name}>{pro.GetValue(entity, null)}</{pro.Name}>");
                                    }
                                }
                            }
                        }
                    }
                }
                xml.Append($"</{nodeName}>");
                return xml.ToString();
            }
        }
    
        public abstract class Entity
        { }
        /// <summary>
        /// 上传明细类
        /// </summary>
        [XmlName("NDEML")]
        public class UploadDetail : Entity
        {
            [IsXmlProperty(true)]
            [XmlName("templateVersion")]
            public string TemplateVersion { get; set; } = "1.0";
    
            public Head Head
            { get; set; }
            public Body Body
            { get; set; }
    
        }
        [XmlName("head")]
        public class Head : Entity
        {
            /// <summary>
            /// 导出时间
            /// </summary>
            public DateTime exportDate { get; set; } = DateTime.Now;
            /// <summary>
            /// 导出数据的业务类型,填写 N707
            /// </summary>
            public string dataType { get; set; } = "N707";
            /// <summary>
            /// 固定填写1
            /// </summary>
            public string sourceType { get; set; } = "1";
            /// <summary>
            /// 固定填写210000
            /// </summary>
            [IsXmlValue(true)]
            public SourceCode SourceCode { get; set; }
            /// <summary>
            /// 固定填写00
            /// </summary>
            public string targetCode { get; set; } = "00";
    
        }
        [XmlName("sourceCode")]
        public class SourceCode : Entity
        {
            public SourceCode(string selfValue)
            {
                SelfValue = selfValue;
            }
            [IsXmlProperty(true)]
            [XmlName("ref")]
            public string Ref { get; set; } = "210000";
    
    
            private string SelfValue
            { get; set; }
    
        }
    
        [XmlName("body")]
        public class Body : Entity
        {
            public List<BodyItem> BodyItems { get; set; } = new List<BodyItem>();
        }
        [XmlName("bodyItem")]
        public class BodyItem : Entity
        {
            [IsXmlProperty(true)]
            [XmlName("itemId")]
            public string ItemId { get; set; }
            ///// <summary>
            ///// 0表示撤销部分项目;1表示撤销该患者本次住院所有上传的费用明细,data中可无内容
            ///// </summary>
            //public int cancelMode { get; set; }
            /// <summary>
            /// 扩展,备用
            /// </summary>
            [XmlName("extendData")]
            public string ExtendData
            { get; set; }
    
            /// <summary>
            /// 主数据
            /// </summary>
            [XmlName("data")]
            public Data Data
            {
                get; set;
            }
    
        }
        [XmlName("data")]
        public class Data : Entity
        {
            public List<Detail> Details
            {
                get; set;
            } = new List<Detail>();
        }
    
        [XmlName("N707")]
        public class Detail : Entity
        {
            /// <summary>
            /// 住院处方流水号   100
            /// </summary>
            [XmlName("N707-01")]
            public string N707_01
            { get; set; }
    
            /// <summary>
            /// 项目序号(费用明细HIS系统唯一标识)    36
            /// </summary>
            [XmlName("N707-02")]
            public string N707_02
            { get; set; }
    
    
        }
    
        /// <summary>
        /// 是否节点值
        /// </summary>
        [AttributeUsage(AttributeTargets.Property)]
        public class IsXmlValueAttribute : Attribute
        {
            public IsXmlValueAttribute(bool isXmlValue)
            {
                IsXmlValue = isXmlValue;
            }
            public bool IsXmlValue
            {
                get; private set;
            }
        }
    
        /// <summary>
        /// 是否xml属性
        /// </summary>
        [AttributeUsage(AttributeTargets.Property)]
        public class IsXmlPropertyAttribute : Attribute
        {
            public IsXmlPropertyAttribute(bool isXmlProperty)
            {
                IsXmlProperty = isXmlProperty;
            }
            public bool IsXmlProperty
            {
                get; private set;
            }
        }
    
        /// <summary>
        /// xml名称特性
        /// </summary>
        [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)]
        public class XmlNameAttribute : Attribute
        {
            public XmlNameAttribute(string xmlName)
            {
                XmlName = xmlName;
            }
    
            public string XmlName
            {
                get;
                private set;
            }
    
    
        }
    }

    在这我也有点偷懒了,实体类之定义了一点点,实现了功能。运行之后是这个效果

     希望对你有所帮助!

  • 相关阅读:
    uva-442 Matrix Chain Multiplication
    mongodb笔记2
    用MODELLER构建好模型后对loop区域进行自动的优化过程
    Java乔晓松-android的四大组件之一Service(服务的绑定)
    内部排序之交换排序
    C,C++中的static
    [置顶] 贝叶斯分类(一)
    RabbitMQ和kafka从几个角度简单的对比--转
    rabbitmq Clustering Guide--官方
    How To Cluster Rabbit-MQ--reference
  • 原文地址:https://www.cnblogs.com/ljknlb/p/7561641.html
Copyright © 2020-2023  润新知