1. 程式人生 > 實用技巧 >以字典形式寫入xml

以字典形式寫入xml

遞迴讀取字典形式的物件,寫入xml檔案

 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); GenerateXML_for_Dic(xmlDoc, xmlDoc, xmlDictionary); } /// <summary> /// 遞迴讀取字典生成xml /// </summary> /// <param name="xmlDoc"></param> /// <param name="parentNode"></param>
/// <param name="xmldic"></param> public void GenerateXML_for_Dic(XmlDocument xmlDoc, XmlNode parentNode, Dictionary<string, object> xmldic) { if (xmldic == null) { return; } foreach (var kvp in xmldic) {
if (kvp.Value == null) { continue; } XmlNode 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>); } } xmlDoc.Save("test.xml"); } }