使用 XML 序列化的循环引用

本文关键字:循环 引用 序列化 XML 使用 | 更新日期: 2023-09-27 18:34:28

我找到了在使用xml序列化时处理循环引用的解决方案。但就我而言,我有一个列表:

public class Category
{
    public Category()
    {
        Items = new List<CategoryItem>();
    }
    public string CategoryName { get; set; }
    public List<CategoryItem> Items { get; set; }
}

和:

public class CategoryItem
{
    public string Link { get; set; }
    public Category Category { get; set; }
}

程序:

  private static void Main(string[] args)
    {
        var programmingCategory = new Category {CategoryName = "Programming"};
        var ciProgramming = new CategoryItem
        {
            Link = "www.stackoverflow.com",
            Category = programmingCategory
        };
        var fooCategory = new CategoryItem
        {
            Category = programmingCategory,
            Link = "www.foo.com"
        };
        programmingCategory.Items.Add(ciProgramming);
        programmingCategory.Items.Add(fooCategory);
        var serializer = new XmlSerializer(typeof (Category));
        var file = new FileStream(FILENAME, FileMode.Create);
        serializer.Serialize(file, programmingCategory);
        file.Close();
    }

我总是得到一个

无效操作异常

我该如何解决这个问题?

使用 XML 序列化的循环引用

你只需更改类别项模型

public class CategoryItem
{
    public string Link { get; set; }
}

修改此代码:

private static void Main(string[] args)
    {
        var programmingCategory = new Category {CategoryName = "Programming"};
        var ciProgramming = new CategoryItem
        {
            Link = "www.stackoverflow.com"
        };
        var fooCategory = new CategoryItem
        {
            Link = "www.foo.com"
        };
        programmingCategory.Items.Add(ciProgramming);
        programmingCategory.Items.Add(fooCategory);
        var serializer = new XmlSerializer(typeof (Category));
        var file = new FileStream(FILENAME, FileMode.Create);
        serializer.Serialize(file, programmingCategory);
        file.Close();
    }

我认为它工作正常。请尝试此代码。我只是更改您的模型并获得此输出。

<?xml version="1.0"?>
-<Category xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<CategoryName>Programming</CategoryName>

-<Items>

-<CategoryItem>
<Link>www.stackoverflow.com</Link>
</CategoryItem>

-<CategoryItem>
<Link>www.foo.com</Link>
</CategoryItem>
</Items>
</Category>