Ejemplo n.º 1
0
        // --------------------------------------------------------------------------------------------------------------------------
        /// <summary>
        /// Deserialize the given XElement into the corresponding type.
        /// </summary>
        /// <remarks>
        /// At this time, this function will only deserialize attributes defined on the fragment.  Child elements
        /// will be ignored.
        /// </remarks>
        public static T DeserializeFragment <T>(XElement src)
            where T : new()
        {
            T    res = new T();
            Type t   = typeof(T);

            var props = ReflectionTools.GetPropertiesWithAttribute <T, XmlAttributeAttribute>().ToList();

            foreach (var p in props)
            {
                // string name = a.Name;
                string     attrName = ReflectionTools.GetAttribute <XmlAttributeAttribute>(p).AttributeName;
                XAttribute xattr    = src.Attribute(attrName);
                if (xattr != null)
                {
                    object val = ReflectionTools.ConvertEx(p.PropertyType, xattr.Value);
                    p.SetValue(res, val, null);
                }
            }


            return(res);
        }
Ejemplo n.º 2
0
        // --------------------------------------------------------------------------------------------------------------------------
        /// <summary>
        /// Serialize the given data to an XML fragment.
        /// </summary>
        public static XElement SerializeFragment <T>(T data)
        {
            Type t        = typeof(T);
            var  rootAttr = ReflectionTools.GetAttribute <XmlRootAttribute>(t);

            string useName = rootAttr == null ? t.Name : rootAttr.ElementName;

            XElement res = new XElement(useName);

            var props = ReflectionTools.GetPropertiesWithAttribute <T, XmlAttributeAttribute>().ToList();

            foreach (var p in props)
            {
                string attrName = ReflectionTools.GetAttribute <XmlAttributeAttribute>(p).AttributeName;
                object value    = p.GetValue(data, null);
                if (value != null)
                {
                    res.Add(new XAttribute(attrName, value));
                }
            }

            return(res);
        }