简体   繁体   中英

How to serialize a nested list in c# into XML without specifying a list element?

I have got two classes:

public class Foo
{
    public string FooName{get;set;}
    public List<Bar> Bars{get;set;}
}

public class Bar
{
    public string BarName{get;set;}
}

If I serialize this using the XML parser I come up with:

<Foo>
    <FooName>ExampleFooName</FooName>
    <Bars>
        <Bar>
             <BarName>ExampleBarName</BarName>
        </Bar>
        <Bar>
             <BarName>AnotherExampleBarName</BarName>
        </Bar>
    </Bars>
<Foo>

Is there any way to receive this as the result:

<Foo>
    <FooName>ExampleFooName</FooName>

    <Bar>
         <BarName>ExampleBarName</BarName>
    </Bar>
    <Bar>
         <BarName>AnotherExampleBarName</BarName>
    </Bar>
<Foo>

I am looking to either restructure the Foo and Bar classes, or pass in some parameter to the XMLSerializer to receive the result. I really want to avoid writing my own XML parser.

public class Foo
{
    public string FooName{get;set;}
    [XmlElement("Bar")]
    public List<Bar> Bars{get;set;}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM