10

Is it possible to avoid list property tags when serializing?

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

Serializing Foo gives (except the comment):

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

Wanted output:

<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
  • [Serializable] has nothing to do with XML Serialization.
    – Cheeso
    May 19, 2009 at 17:35

1 Answer 1

12

Adding:

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

Results in

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.