So I am trying to simply decorate a class to serialize it as XML. Here's an example of my problem.
[XmlElement("Dest")]
public XmlNode NewValue { get; set; }
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:
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.
I tried the XmlAnyAttribute, but that failed as well. So simply put, how can I serialize an XmlNode?
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.
[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) && (value.NodeType == XmlNodeType.Element) && ((value.ChildNodes == null) || (value.ChildNodes.Count == 0)))
{
OldValue = value.Attributes[0];
}
else
{
OldValue = value;
}
}
}