Note that there are some explanatory texts on larger screens.

plurals
  1. POCustom XML-element name for base class field in serialization
    text
    copied!<p>How can I change XML-element name for field inherited from base class while doing serialization?</p> <p>For example I have next base class:</p> <pre><code>public class One { public int OneField; } </code></pre> <p>Serialization code:</p> <pre><code>static void Main() { One test = new One { OneField = 1 }; var serializer = new XmlSerializer(typeof (One)); TextWriter writer = new StreamWriter("Output.xml"); serializer.Serialize(writer, test); writer.Close(); } </code></pre> <p>I get what I need:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;One xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt; &lt;OneField&gt;1&lt;/OneField&gt; &lt;/One&gt; </code></pre> <p>Now I have created new class inherited from <code>A</code> with additional field and custom XML element name for it:</p> <pre><code>public class Two : One { [XmlElement("SecondField")] public int TwoField; } </code></pre> <p>Serialization code:</p> <pre><code>static void Main() { Two test = new Two { OneField = 1, TwoField = 2 }; var serializer = new XmlSerializer(typeof (Two)); TextWriter writer = new StreamWriter("Output.xml"); serializer.Serialize(writer, test); writer.Close(); } </code></pre> <p>As a result I get next output:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;Two xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt; &lt;OneField&gt;1&lt;/OneField&gt; &lt;SecondField&gt;2&lt;/SecondField&gt; &lt;/Two&gt; </code></pre> <p>The problem is that I want to change <code>OneField</code> in this output to <code>FirstField</code> without touching base class code (because I will use it too and the names must be original). How can I accomplish this?</p> <p>Thank you.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload