1

i am serializing xml files using the XmlSerializer. It works just fine:

[XmlRoot(ElementName = "Wire"]
public class Wire
{
    [XmlElement(ElementName = "Powerrail"]
    public string Powerrail { get; set; }

    [XmlElement(ElementName = "IdentCon"]
    public IdentCon IdentCon { get; set; }

    [XmlElement(ElementName = "NameCon"]
    public List<NameCon> NameCon { get; set; }

    [XmlAttribute(AttributeName = "UId")]
    public string UId { get; set; }
}

<Wire UId="62">
    <NameCon UId="51" Name="out" />
    <NameCon UId="52" Name="in" />
</Wire>
<Wire UId="63">
    <IdentCon UId="22" />
    <NameCon UId="52" Name="operand" />
</Wire>
<Wire UId="64">
   <NameCon UId="52" Name="out" />
   <NameCon UId="53" Name="i_xOff1" />
</Wire>

But now i want to add comments to the xml file, something like this:

<Wire UId="62"> <!-- Wire from Location 1 -->
    <NameCon UId="51" Name="out" />
    <NameCon UId="52" Name="in" />
</Wire>
<Wire UId="63"> <!-- Wire from Location 2 -->
    <IdentCon UId="22" />
    <NameCon UId="52" Name="operand" />
</Wire>
<Wire UId="64"> <!-- Wire from Location 3 -->
   <NameCon UId="52" Name="out" />
   <NameCon UId="53" Name="i_xOff1" />
</Wire>

Can i achieve this using the XmlSerializer? Thanks a lot!

Felix
  • 87
  • 10
  • I'm not aware of any inbuilt way to do this, short of IXmlSerializable, which (and u cannot emphasize this enough) you should generally avoid (it is very hard to get it right): https://stackoverflow.com/a/7386148/23354 – Marc Gravell Jun 24 '21 at 09:33
  • It's actually fairly easy to insert a comment into an XML file using `XmlSerializer`, see https://stackoverflow.com/a/46497304/3744182. However, in the *`Wire from Location X`* comment, is the index `X` a property of `Wire`? Or the index in some containing collection? If an index of the container and there's no way to access that index from `Wire` then you will need to implement `IXmlSerializable` ***on the containing collection*** which will indeed be extremely inconvenient and difficult to get correct as @MarcGravell wrote. Honestly not recommended for something that is ignored anyway. – dbc Jun 24 '21 at 15:34
  • 1
    Thank both of you. Yes, the index will be a property of wire. But i ecided to leave the comments out anyway. – Felix Jun 25 '21 at 11:30

0 Answers0