zoukankan      html  css  js  c++  java
  • 以字典形式写入xml

    递归读取字典形式的对象,写入xml文件

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Xml;
    
    namespace test1
    {
        class XmlGenerator
        {
            /// <summary>
            /// xml生成类
            /// </summary>
    
            public XmlGenerator(Dictionary<string, object> xmlDictionary)
            {
                XmlDocument xmlDoc = new XmlDocument();
                //创建类型声明节点  
                XmlNode node = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "");
                xmlDoc.AppendChild(node);
                xmlDoc = GenerateXML_for_Dic(xmlDoc, xmlDoc, xmlDictionary);
                xmlDoc.Save("test.xml");
            }
    
            /// <summary>
            /// 递归读取字典生成xml
            /// </summary>
            /// <param name="xmlDoc"></param>
            /// <param name="parentNode"></param>
            /// <param name="xmldic"></param>
            public XmlDocument GenerateXML_for_Dic(XmlDocument xmlDoc, XmlNode parentNode, Dictionary<string, object> xmldic)
            {
                XmlNode node;
                if (xmldic == null)
                {
                    return null;
                }
                foreach (var kvp in xmldic)
                {
                    if (kvp.Value == null)
                    {
                        continue;
                    }
                    if (kvp.Key.Contains("objects"))//改object名字
                    {
                        int index = kvp.Key.IndexOf("objects");
                        node = xmlDoc.CreateNode(XmlNodeType.Element, kvp.Key.Remove(index + 6), null);//创建节点
                    }
                    else
                    {
                        node = xmlDoc.CreateNode(XmlNodeType.Element, kvp.Key, null);//创建节点
                    }
                    if (kvp.Value is string)
                    {
                        node.InnerText = kvp.Value.ToString();
                    }
                    parentNode.AppendChild(node); //将子节点加入父节点
                    if (kvp.Value is IDictionary)
                    {
                        GenerateXML_for_Dic(xmlDoc, node, kvp.Value as Dictionary<string, object>);
                    }
                }
    
                return xmlDoc;
            }
        }
    }
  • 相关阅读:
    MYSQL 使用DBI
    mysql 更改数据目录
    Error Code: 1360
    org.hibernate.exception.GenericJDBCException: Could not open connection
    Error: Dynamic is undefined
    Unhandled event loop exception No more handles
    Count:858org.apache.jasper.JasperException: Unable to compile class for JSP
    Mysql --skip-grant-table
    第24章-启动 停止 和配置mysql
    Linux 6.2 x86_64 安装ipvs
  • 原文地址:https://www.cnblogs.com/Manuel/p/13519426.html
Copyright © 2011-2022 走看看