使用XML序列化的循环引用

时间:2016-02-14 08:46:44

标签: c# xml serialization

我找到了handling circular reference when using xml serialization的解决方案。但就我而言,我有一个清单:

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();
    }

我总是得到一个

  

出现InvalidOperationException

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您只需更改CategoryItem模型

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>