向XML序列化添加递归文件夹结构
本文关键字:文件夹 结构 递归 添加 XML 序列化 | 更新日期: 2023-09-27 18:13:19
我有一个c#项目,它将对象列表序列化为xml。
[Serializable]
[XmlRoot]
public class collection {
private List<item> _items = new List<item>();
[XmlElement("item")]
public List<item> items {
get { return _items; }
}
}
[Serializable]
public class item {
}
则XML输出为
<collection>
<item/>
<item/>
<item/>
</collection>
我想要的是添加folders&子文件夹选项,以便项目可以分组在一起,同时仍然能够进入根节点。
<collection>
<item/>
<item/>
<folder>
<item/>
<item/>
</folder>
<item/>
<item/>
<folder>
<item/>
<item/>
<folder>
<item/>
<item/>
</folder>
</folder>
<item/>
</collection>
谁能建议一个干净的方式这样做,同时继续使用序列化对象生成xml输出?
这必须是类结构。
public class Folder2
{
}
public class Folder
{
public Folder2 folder { get; set; }
}
public class Collection
{
public List<Folder> folder { get; set; }
}
public class RootObject
{
public Collection collection { get; set; }
}
经过一些尝试和错误,我成功地获得了我想要的功能。
[Serializable]
[XmlRoot]
public class collection {
private List<treeEntry> _entries = new List<treeEntry>();
[XmlElement("item", typeof(item))]
[XmlElement("folder", typeof(folder))]
public List<treeEntry> entries {
get { return _entries; }
}
}
public abstract class treeEntry { }
[Serializable]
public class folder : treeEntry {
private List<treeEntry> _entries = new List<treeEntry>();
public folder() { }
[XmlAttribute]
public string name { get; set; }
[XmlElement("item", typeof(item))]
[XmlElement("folder", typeof(folder))]
public List<treeEntry> entries {
get { return _entries; }
}
}
[Serializable]
public class item : treeEntry { }
public class mytest {
public static void main() {
collection col = new collection();
col.entries.Add(new item());
col.entries.Add(new item());
var folder1 = new folder() { name = "someFolder" };
folder1.entries.Add(new item());
var folder2 = new folder() { name = "anotherFolder" };
folder1.entries.Add(folder2);
folder1.entries.Add(new item());
folder2.entries.Add(new item());
col.entries.Add(folder1);
col.entries.Add(new folder());
col.entries.Add(new item());
XmlSerializer sers = new XmlSerializer(typeof(collection));
//serialise
using (StreamWriter sw = new StreamWriter("testoutput.xml", false, Encoding.UTF8)) {
XmlWriter xw = new XmlTextWriter(sw);
sers.Serialize(xw, col);
}
//deserialise
FileStream fs = new FileStream("testoutput.xml", FileMode.Open);
XmlReader reader = XmlReader.Create(fs);
collection newcol = (collection)sers.Deserialize(reader);
//output to console
sers.Serialize(Console.Out, newcol);
}
}
产生期望的输出
<collection>
<item />
<item />
<folder name="someFolder">
<item />
<folder name="anotherFolder">
<item />
</folder>
<item />
</folder>
<folder />
<item />
</collection>