加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何抑制列表属性的XML标签

发布时间:2020-12-15 06:46:04 所属栏目:百科 来源:网络整理
导读:序列化时是否可以避免列表属性标签? //[Serializable()] - removed,unnecessarypublic class Foo{ protected ListFooBar fooBars = new ListFooBar(); public virtual ListFooBar FooBars { get { return fooBars; } set { fooBars = value; } }}// [Serial
序列化时是否可以避免列表属性标签?
//[Serializable()] - removed,unnecessary
public class Foo
{
    protected List<FooBar> fooBars = new List<FooBar>();
    public virtual List<FooBar> FooBars
    {
        get { return fooBars; }
        set { fooBars = value; }
    }
}

// [Serializable()] - removed,unnecessary
public class FooBar
{
    public int MyProperty
    { get; set; }
}

序列化Foo给出(注释除外):

<Foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <FooBars>    <!-- Unwanted tag -->
    <FooBar>
      <MyProperty>7</MyProperty> 
    </FooBar>
    <FooBar>
      <MyProperty>9</MyProperty> 
    </FooBar>
  </FooBars>
</Foo>

想输出:

<Foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <FooBar>
    <MyProperty>7</MyProperty> 
  </FooBar>
  <FooBar>
    <MyProperty>9</MyProperty> 
  </FooBar>

解决方法

添加:
[System.Xml.Serialization.XmlElement("FooBar")]
public virtual List<FooBar> FooBars 
{ 
    get { return fooBars; } 
    set { fooBars = value; }
}

结果是

<FooMain xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http:/
/www.w3.org/2001/XMLSchema">
  <FooBar>
    <MyProperty>7</MyProperty>
  </FooBar>
  <FooBar>
    <MyProperty>76</MyProperty>
  </FooBar>
  <FooBar>
    <MyProperty>67</MyProperty>
  </FooBar>
</FooMain>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读