0

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.

asked Mar 23, 2022 at 12:49
1
  • Hi! This is the way how the next system will deserialize this xml file correctly, and I don't have control over it. Commented Mar 23, 2022 at 12:59

1 Answer 1

2

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.

answered Mar 23, 2022 at 13:12
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.