c# - 在将XML中的子项列表解析为C#中的对象时如何保持父元素引用 [英] How to keep parent element reference while parsing list of children in XML to Object in c#

查看:28
本文介绍了c# - 在将XML中的子项列表解析为C#中的对象时如何保持父元素引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望在子对象中保留父节点的 trak,以便在任何时候我都可以立即访问父节点并访问其属性,也可以遍历兄弟节点.

Want to keep trak of parent node in child object so that at any point I can go to immidiate parent and access its attributes and also can traverse siblings.

XML:

<Parent Name"P1">
    <Child Name="C1">
        <GChild Name="GC1"/>
        <GChild  Name="GC2"/>
    </Child>
    <Child Name="C2">
        <GChild  Name="GC3"/>
        <GChild  Name="GC4"/>
    </Child>
</Parent> 

班级:

[Serializable]
public class Parent
{
    [XmlAttribute]
    public string Name { get; set; }

    [XmlElement(ElementName = "Child")]
    public List<Child> Children { get; set; }

    public class Child
    {
        public Parent Parent { get; get;} //Want to know who is its parent.

        [XmlAttribute]
        public string Name { get; set; }

        [XmlElement(ElementName = "GChild")]
        public List<GChild> Children { get; set; }

        public class GChild
        {
            public Child Parent { get; set; } //Want to know who is its parent.

            [XmlAttribute]
            public string Name { get; set; }
        }
    }
}

解析:

var serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(new StringReader(xml));

在所有子元素中创建了其父类型的名为 Parent 的属性,但不知道如何分配它.它的 null 现在.对象类需要做哪些改变?

Created the property named Parent of its parent type in all child elements but don't know what to do to assign it. Its null for now. What changes are needed to be done in object class?

推荐答案

您可以创建自定义集合来保存有关儿童的信息.将项目添加到此集合时,您将设置序列化/反序列化时应忽略的 Parent 属性 (XmlIgnoreAttribute).
阅读这个.我认为这正是您要搜索的内容.

You could create custom collection to hold information about children. When items will be added to this collection you would set Parent property that should be ignored (XmlIgnoreAttribute) when serializeing/deserializing.
Read this. I think it is exactly wnat you search for.

这篇关于c# - 在将XML中的子项列表解析为C#中的对象时如何保持父元素引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆