rename property in xml schema class when serializing

1.1k views Asked by At

I have an auto generated c# class file from an xml schema using the xsd generator tool.

There is a property in this class that i need to rename from "Balance" to "balance" when the xml file gets created.

As this is a generated class i need to update the created xml object on the fly before seralizing so cant just add an atrribute over the class property with the expected name.

I have accomplished the task of ignoring certain properties by using the XmlAttributes class so am sure there is something i could do along same lines for this

Can anyone point me in the direction of how to achieve this?

Thanks

2

There are 2 answers

1
AdrianSean On BEST ANSWER

I have managed to resolve my issue by using the following:

var overrides = new XmlAttributeOverrides();  

overrides.Add(typeof(MyGeneratedCustomType), "Balance", new XmlAttributes { XmlAttribute = new XmlAttributeAttribute("balance") });

var serializer = new XmlSerializer(xmlFile.GetType(), overrides);

MyGeneratedCustomType is a type that appears in the generated xsd class which holds the property i needed to rename. Its an elegant solution as there is very minimal code required.

2
Dan Field On

Assuming you need to deserialize from XML like this:

<root>
  <Balance />
</root>

and then serialize to XML like this:

<root>
  <balance />
</root>

You have two options here:

  1. You could just create a second class that mirrors your auto-generated class in every way except for having [XmlElement("balance")] on the Balance property in the mirrored class. If the generated class is XsdGenerated and the mirrored class is CustomClass, create a constructor or override the =s operator to be able to populate the CustomClass with all the fields from XsdGenerated. When you serialize CustomClass, you should get the desired result. I think this is the preferable option.

  2. Implement IXmlSerializable on XsdGenerated. Call base() in the ReadXml method, and just have the WriteXml method create the balance tag in lower case. Note that this option is probably more challenging to write/maintain and would limit your ability to serialize and deserialize - it'd be a one way operation, unless you created an even more complex mechanism to set whether ReadXml() and WriteXml() should treat balance with an upper or lower case b.