title: .NET Serialize XmlNode problem
body: <p>So I am trying to simply decorate a class to serialize it as XML. Here's an example of my problem.</p>
  
  <pre><code>[XmlElement("Dest")]
      public XmlNode NewValue { get; set; }
  </code></pre>
  
  <p>The real problem here is that sometimes in this implementation the XmlNode can be an XmlElement or XmlAttribute. when it's an element this code works fine, but when it comes through as an attribute the serializer throws the following error:</p>
  
  <p>System.InvalidOperationException: Cannot write a node of type XmlAttribute as an element value. Use XmlAnyAttributeAttribute with an array of XmlNode or XmlAttribute to write the node as an attribute.</p>
  
  <p>I tried the XmlAnyAttribute, but that failed as well. So simply put, how can I serialize an XmlNode?</p>
  
  <p>For the record, I marked the correct answer below. You kinda got to hack it. Here's roughly what I implemented myself in case anyone else hits this.</p>
  
  <pre><code>    [XmlIgnore()]
      public XmlNode OldValue { get; set; }
  
      [XmlElement("Dest")]
      public XmlNode SerializedValue
      {
          get
          {
              if (OldValue == null)
              {
                  return null;
              }
              if (OldValue.NodeType == XmlNodeType.Attribute)
              {
                  XmlDocumentFragment frag = OldValue.OwnerDocument.CreateDocumentFragment();
  
                  XmlElement elem = (frag.OwnerDocument.CreateNode(XmlNodeType.Element, "SerializedAttribute", frag.NamespaceURI) as XmlElement);
  
                  elem.SetAttribute(OldValue.Name, OldValue.Value);
  
                  return elem;
              }
              else
              {
                  return OldValue;
              }
          }
          set
          {
              if (value == null)
              {
                  OldValue = null;
                  return;
              }
              if ((value.Attributes != null) &amp;&amp; (value.NodeType == XmlNodeType.Element) &amp;&amp; ((value.ChildNodes == null) || (value.ChildNodes.Count == 0)))
              {
                  OldValue = value.Attributes[0];
              }
              else
              {
                  OldValue = value;
              }
          }
      }
  </code></pre>