反序列化xml结构,并通过Indexers访问 [英] Deserializing xml structure, and accessing through Indexers

查看:94
本文介绍了反序列化xml结构,并通过Indexers访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


您好,

推荐答案

您可以在列表(A和B)上创建索引器,将遍历值以找到一个匹配,如下例所示。

You can create indexers on the Lists (of A and B), which would iterate through the values to find one matching, like in the example below.

  public class Post_3588c5e3_3a1b_4252_a437_de560effc624
  {
    [XmlRoot(ElementName = "A_list")]
    public class A_list : List<A>
    {
      public A this[string name]
      {
        get
        {
          foreach (A a in this)
          {
            if (a.Name == name) return a;
          }

          return null;
        }
      }
    }

    public class A
    {
      B_list listB;

      string name;

      public A() { listB = new B_list(); }

      [XmlArray(ElementName = "B_list")]
      [XmlArrayItem(ElementName = "B")]
      public B_list ListB
      {
        get { return listB; }
        set { listB = value; }
      }

      [XmlAttribute(AttributeName = "name")]
      public string Name
      {
        get { return name; }
        set { name = value; }
      }
    }

    public class B_list : List<B>
    {
      public B this[string name]
      {
        get
        {
          foreach (B b in this)
          {
            if (b.Name == name) return b;
          }

          return null;
        }
      }
    }

    public class B
    {
      String name;
      String id;

      [XmlAttribute(AttributeName = "name")]
      public String Name
      {
        get { return name; }
        set { name = value; }
      }

      [XmlAttribute(AttributeName = "id")]
      public String Id
      {
        get { return id; }
        set { id = value; }
      }
    }

    const string xml = @"<A_list>
  <A name=""a1_name"">
    <B_list>
      <B name=""b1_name"" id=""b1_id"" />
      <B name=""b2_name"" id=""b2_id"" />
      <B name=""b3_name"" id=""b3_id"" />
    </B_list>
  </A>
  <A name=""a2_name"">
    <B_list>
      <B name=""b1_name"" id=""b1_id"" />
      <B name=""b2_name"" id=""b2_id"" />
      <B name=""b3_name"" id=""b3_id"" />
    </B_list>
  </A>
</A_list>";

    public static void Test()
    {
      XmlSerializer ser = new XmlSerializer(typeof(A_list));
      XmlReader xmlReader = XmlReader.Create(new MemoryStream(Encoding.UTF8.GetBytes(xml)));
      A_list listA = (A_list)ser.Deserialize(xmlReader);
      Console.WriteLine(listA[0].ListB[1].Id);
      Console.WriteLine(listA[0].ListB[1].Name);
      Console.WriteLine(listA["a1_name"].ListB["b2_name"].Id);
    }
  }


这篇关于反序列化xml结构,并通过Indexers访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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