递归读取字典形式的对象,写入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; } } }