Click here to Skip to main content
15,891,409 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi everyone,
I tried convert from an object to xml file. There is parent-child relation in object like below. I convert it, no problem. Is there another way or any trick better than my solution(in Load Function of Parent Class)?, because I will convert a graph to xml file. Maybe, I will face the same problem for edges. How can I solve reference problem?

 public class FileService<T>
{
    public void Save(T obj, string filePath)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        TextWriter writer = new StreamWriter(filePath);
        serializer.Serialize(writer, obj);
        writer.Close();
    }

    public T Load(string filePath)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        TextReader reader = new StreamReader(filePath);
        var obj = (T)serializer.Deserialize(reader);
        reader.Close();
        return obj;
    }
}

public class Parent
{
    List<Child> children;

    [XmlArray("Children")]
    [XmlArrayItem("Child")]
    public List<Child> Children
    {
        get
        {
            if (children == null)
                children = new List<Child>();
            return children;
        }
        set { children = value; }
    }


    public void AddChild(Child child)
    {
        child.Parent = this;
        Children.Add(child);
    }

    public static Parent Load(string path)
    {
        FileService<Parent> fileService = new FileService<Parent>();
        var parent = fileService.Load(path);
        parent.Children.ForEach(child => child.Parent = parent);
        return parent;
    }
}

public class Child
{
    int value;
    Parent parent;

    [XmlIgnore]
    public Parent Parent
    {
        get { return parent; }
        set { parent = value; }
    }

    [XmlElement("Value")]
    public int Value
    {
        get
        {
            return this.value;
        }
        set { this.value = value; }
    }

    public Child()
    {

    }

    public Child(int value)
    {
        this.value = value;
    }
}
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900