Exemplo n.º 1
0
        private void WriteXmlValue(XmlWriter writer, IHierarchy <object> node)
        {
            if (node.IsNodeEnumerable())
            {
                return;
            }

            var converter = Converters.FirstOrDefaultWriterConverter(node.InstanceType);

            if (converter != null)
            {
                converter.WriteXml(writer, node.Instance);
                return;
            }

            bool hasAttributeAttribute = node.HasMemberReference && TypeUtility.ContainsAttributeType(node.MemberReference, typeof(XmlAttributeAttribute));
            bool hasElementAttribute   = node.HasMemberReference && TypeUtility.ContainsAttributeType(node.MemberReference, typeof(XmlElementAttribute));
            bool hasTextAttribute      = node.HasMemberReference && TypeUtility.ContainsAttributeType(node.MemberReference, typeof(XmlTextAttribute));

            bool   isType   = node.Instance is Type;
            Type   nodeType = isType ? (Type)node.Instance : node.InstanceType;
            string attributeOrElementName = XmlUtility.SanitizeElementName(node.HasMemberReference ? node.MemberReference.Name : StringConverter.FromType(nodeType));

            if (!hasAttributeAttribute && !hasElementAttribute && !hasTextAttribute)
            {
                hasElementAttribute = true; // default serialization value for legacy Cuemon
                if ((!TypeUtility.IsComplex(nodeType) || isType) && !node.HasChildren && (isType))
                {
                    if (!node.HasParent)
                    {
                        hasElementAttribute = false;
                    }
                    hasTextAttribute = true;
                }
            }
            else
            {
                string elementName = null;
                if (hasAttributeAttribute)
                {
                    elementName = node.MemberReference.GetCustomAttribute <XmlAttributeAttribute>().AttributeName;
                }
                if (hasElementAttribute)
                {
                    elementName = node.MemberReference.GetCustomAttribute <XmlElementAttribute>().ElementName;
                }

                if (!string.IsNullOrEmpty(elementName))
                {
                    attributeOrElementName = elementName;
                }
            }

            var value = Wrapper.ParseInstance(node);

            if (hasAttributeAttribute)
            {
                writer.WriteAttributeString(attributeOrElementName, value);
            }
            else if (hasElementAttribute)
            {
                if (node.HasMemberReference)
                {
                    writer.WriteElementString(attributeOrElementName, value);
                }
                else
                {
                    writer.WriteValue(value);
                }
            }
            else if (hasTextAttribute)
            {
                writer.WriteString(value);
            }
        }