So I'm trying to just decorate the class to serialize it as XML. Here is an example of my problem.
[XmlElement("Dest")]
public XmlNode NewValue { get; set; }
The real problem is that sometimes in this implementation, the XmlNode can be either XmlElement or XmlAttribute. when it is an element, this code works fine, but when it comes as an attribute, the serializer throws the following error:
System.InvalidOperationException: Unable to write node of type XmlAttribute as element value. Use XmlAnyAttributeAttribute with an XmlNode or XmlAttribute array to write the node as an attribute.
I tried XmlAnyAttribute, but that also failed. So simple to put, how can I serialize an XmlNode?
For the record, I indicated the correct answer below. You have to hack it. Here is about what I implemented myself, in case someone else hit 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;
}
}
}
source
share