Как подавить тег XML для свойства списка - PullRequest
10 голосов
/ 24 ноября 2008

Можно ли избежать тегов свойств списка при сериализации?

//[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>

1 Ответ

12 голосов
/ 24 ноября 2008

Добавление:

[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>
...