title: Would it be possible to serialize a union like C# struct to XML?
body: <p>Lets say I have this simple (union like) C# struct  </p>
  
  <pre><code>[StructLayout(LayoutKind.Explicit)]
  public struct MyData
  {
      [FieldOffset(0)]
      public int Num;
      [FieldOffset(0)]
      public int Number;
      [FieldOffset(4)]
      public string Name;
      [FieldOffset(4)]
      public string Url;
  };
  </code></pre>
  
  <p>And a save method that uses XmlSerializer and StreamWriter </p>
  
  <pre><code>static void SaveToXml(object obj, string fileName)
  {
      XmlSerializer writer = new XmlSerializer(obj.GetType());
      using (StreamWriter file = new StreamWriter(fileName))
      {
          writer.Serialize(file, obj);
      }
  }
  </code></pre>
  
  <p>So if we'd put some data in and save it: </p>
  
  <pre><code>MyData md = new MyData();
  md.Name = "Ilan_01";
  md.Num = 1;
  SaveToXml(md, @"C:\temp\data.xml");
  </code></pre>
  
  <p>XML File would look like this:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;MyData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
    &lt;Num&gt;1&lt;/Num&gt;
    &lt;Number&gt;1&lt;/Number&gt;
    &lt;Name&gt;Ilan_01&lt;/Name&gt;
    &lt;Url&gt;Ilan_01&lt;/Url&gt;
  &lt;/MyData&gt;
  </code></pre>
  
  <p>Would it be possible to make it look like this (using the same or similar method)??</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;MyData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
    &lt;Num&gt;1&lt;/Num&gt;
    &lt;Name&gt;Ilan_01&lt;/Name&gt;
  &lt;/MyData&gt;
  </code></pre>
  
  <p><strong>EDIT</strong></p>
  
  <p>On the other hand if we'd set this data:</p>
  
  <pre><code>md = new MyData();
  md.Url = "127.0.0.1";
  md.Number = 2;
  </code></pre>
  
  <p>I'd like to see this XML as out come.</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;MyData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
    &lt;Number&gt;2&lt;/Number&gt;
    &lt;Url&gt;127.0.0.1&lt;/Url&gt;
  &lt;/MyData&gt;
  </code></pre>
  
  <p>So the <code>XmlIgnore</code> attribute isn't what I'm looking for.</p>
  
  <p>This is just a simple example, the real implementation is with different types (same size) of other structs.</p>
  
  <p><strong>End Edit</strong></p>
  
  <p>Thanks, Ilan</p>