Home > Enterprise >  Change the way how list is serialized into XML
Change the way how list is serialized into XML

Time:03-24

So, I have a class with a list of objects like this:

public int SourceId { get; set; }
public int TargetId { get; set; }
public List<ExtraParameter> ExtraParameters { get; }

Then, when it is serialized into XML file, the output is like this:

<Connection>
    <SourceId>0</SourceId>
    <TargetId>1</TargetId>
    <ExtraParameters>
      <ExtraParameter>
        <Input>0</Input>
        <Output>1</Output>
        <Enabled>true</Enabled>
      </ExtraParameter>
      <ExtraParameter>
        <Input>1</Input>
        <Output>0</Output>
        <Enabled>true</Enabled>
      </ExtraParameter>
     </ExtraParameters>
</Connection>

But I need to serialize this array of elements (ExtraParameter) using C#'s XmlSerializer into this form:

<Connection>
   <SourceId>0</SourceId>
   <TargetId>1</TargetId>
   <ExtraParameter>
      <Input>0</Input>
      <Output>1</Output>
      <Enabled>true</Enabled>
   </ExtraParameter>
   <ExtraParameter>
      <Input>1</Input>
      <Output>0</Output>
      <Enabled>true</Enabled>
   </ExtraParameter>
</Connection>

So in other words, can I somehow just list the items in that ExtraParameters-list without having that list in this hierarchy? So it does look like objects in the ExtraParameters are just listed at the end of the TargetID-node.

edit: Yes, I know, this kinda breaks the structure, but this xml file is then deserialized by the next program correctly, and I don't have control over that.

CodePudding user response:

You can do this by adding the XmlElement attribute to the relevant property. Per the docs:

If you apply the XmlElementAttribute to a field or property that returns an array, the items in the array are encoded as a sequence of XML elements.

[XmlElement("ExtraParameter")]
public List<ExtraParameter> ExtraParameters { get; }

You could also change the property name rather than adding a value for ElementName to the attribute.

See this fiddle for a working demo.

  • Related