且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

读取xml节点值生成一个实体类,读取xml所有节点值,读取所有xml所有节点名称

更新时间:2022-10-01 13:10:57

  public partial class WebFormClassByEntity : System.Web.UI.Page
    {
        List<string> list = new List<string>();//存放所有节点名称
        protected void Page_Load(object sender, EventArgs e)
        {
            //读取xml的文件路径
            string filePaht = Server.MapPath("~/KJ881101REC_GDXYKJWL_20150519112906795045.xml");
            getxml(filePaht, list);
            ClaseEntity();
        }


        /// <summary>
        /// 获取指定路径下XML的所有节点值
        /// </summary>
        public List<string> getxml(string xmlFilePath, List<string> list)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                if (File.Exists(xmlFilePath))
                {
                    doc.Load(xmlFilePath);
                    XmlNodeList xnl = doc.DocumentElement.ChildNodes;
                    GetAllNodes(xnl, list);
                }
                else
                {
                    list.Add("Error:");
                    list.Add("Please make sure the path and file are correct!!");
                }
                return list;

            }
            catch (Exception e)
            {
                throw e;
            }
        }

        /// <summary>
        /// 递归遍历所有节点
        /// </summary>
        /// <param name="nodelist"></param>
        /// <param name="listnode"></param>
        /// <returns></returns>
        public List<string> GetAllNodes(XmlNodeList nodelist, List<string> listnode)
        {

            foreach (XmlElement element in nodelist)
            {
                //如果这个节点没有出现过,则添加到list列表
                if (!listnode.Contains(element.Name))
                {
                    listnode.Add(element.Name);
                }
                if (element.ChildNodes[0] is XmlText)
                {
                    continue;
                }
                else
                {
                    GetAllNodes(element.ChildNodes, listnode);
                }
            }
            return listnode;
        }

        /// <summary>
        /// 生成实体类
        /// </summary>
        public void ClaseEntity()
        {
            //准备一个代码编译器单元
            CodeCompileUnit unit = new CodeCompileUnit();
            //准备必要的命名空间(这个是指要生成的类的空间)
            CodeNamespace sampleNamespace = new CodeNamespace("测试_命名空间");//命名空间名称
            //导入必要的命名空间
            sampleNamespace.Imports.Add(new CodeNamespaceImport("System"));//引用的命名空间
            sampleNamespace.Imports.Add(new CodeNamespaceImport("System.Xml"));//引用的命名空间
            //准备要生成的类的定义
            CodeTypeDeclaration Customerclass = new CodeTypeDeclaration("Customer");//类名称
            //指定这是一个Class
            Customerclass.IsClass = true;
            Customerclass.TypeAttributes = TypeAttributes.Public | TypeAttributes.Public;
            //把这个类放在这个命名空间下
            sampleNamespace.Types.Add(Customerclass);
            //把该命名空间加入到编译器单元的命名空间集合中
            unit.Namespaces.Add(sampleNamespace);
            string outputFile = "E://work//生成实体类程序//WebApplication1//WebApplication1//Customer.cs";//生成的类存放的路径 //这是输出文件

            //List<string> list = new List<string>();
            //list.Add("id");
            //list.Add("name");
            foreach (var types in list)
            {
                //添加字段
                CodeMemberField field = new CodeMemberField(typeof(System.String), "_" + types);
                field.Attributes = MemberAttributes.Private;
                Customerclass.Members.Add(field);

                //添加属性
                CodeMemberProperty property = new CodeMemberProperty();
                property.Attributes = MemberAttributes.Public | MemberAttributes.Final;
                property.Name = types;
                property.HasGet = true;
                property.HasSet = true;
                property.Type = new CodeTypeReference(typeof(System.String));

                property.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_" + types)));

                property.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_" + types), new CodePropertySetValueReferenceExpression()));

                Customerclass.Members.Add(property);
            }

            Customerclass.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(SerializableAttribute))));
            //生成代码
            CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
            CodeGeneratorOptions options = new CodeGeneratorOptions();
            options.BracingStyle = "C";
            options.BlankLinesBetweenMembers = true;
            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(outputFile))
            {
                provider.GenerateCodeFromCompileUnit(unit, sw, options);
            }
        }

    }

本文转自程序猿博客51CTO博客,原文链接http://blog.51cto.com/haihuiwei/1677956如需转载请自行联系原作者


365850153