以字典形式生成xml
阿新 • • 發佈:2020-08-12
層級字典構造:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace test1 { public class ToDic { public ToDic(Annotation annotation) { _annotation = annotation; }public Annotation _annotation; public class Annotation { public string _folder; public string _filename; public string _path; public Source _source; public Size _size; public string _segmented; public_Object _object1; public _Object _object2; public Annotation(string folder, string filename, string path, Source source, Size size, string segmented, _Object object1 = null, _Object object2= null)//構造器 { _folder = folder; _filename = filename; _path = path; _source = source; _size = size; _segmented = segmented; _object1 = object1; _object2 = object2; } public class Source { public string _database; public Source(string database)//構造器 { _database = database; } } public class Size { public string _width; public string _height; public string _depth; public Size(string width, string height, string depth)//構造器 { _width = width; _height = height; _depth = depth; } } public class _Object { public string _name; public string _pose; public string _truncated; public string _difficult; public Bndbox _bndbox; public _Object(string name, string pose, string truncated, string difficult, Bndbox bndbox)//構造器 { _name = name; _pose = pose; _truncated = truncated; _difficult = difficult; _bndbox = bndbox; } public class Bndbox { public string _xmin; public string _ymin; public string _xmax; public string _ymax; public Bndbox(string xmin, string ymin, string xmax, string ymax)//構造器 { _xmin = xmin; _ymin = ymin; _xmax = xmax; _ymax = ymax; } } } } public static Dictionary<string, object> ToDictionary(object o) { if (o == null) { return null; } var fileds = o.GetType().GetFields(); Dictionary<string,object> dic = new Dictionary<string, object>(); foreach (var field in fileds) { if (field != null) { if (field.FieldType == typeof(string)) { dic.Add(field.Name, field.GetValue(o)); // foreach (var kvp in dic) // { // Console.WriteLine($"{kvp.Key}:{kvp.Value}"); // } } else { dic.Add(field.Name, ToDictionary(field.GetValue(o))); } } } return dic; } } }
/// <summary> /// 遞迴列印字典 /// </summary> /// <param name="o"></param> /// <param name="emp"></param> public static void LoopPrint(object o, string emp = "") { Dictionary<string, object> dic = o as Dictionary<string, object>; if (dic==null) { return; } foreach (var kvp in dic) { if (kvp.Value == null) { return; } if (kvp.Value.GetType() == typeof(string)) { Console.WriteLine(emp + $"{kvp.Key}:{kvp.Value}"); } else { Console.WriteLine(emp + $"{kvp.Key}:"); LoopPrint(kvp.Value, emp + " "); Console.WriteLine(emp + $"{kvp.Key}"); } } }