コード例 #1
0
        // public DataSourceXml(): this(new XmlSerializerSettings())
        /// <summary>
        /// Initializes a new instance of the <see cref="DataSourceXml"/> class.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <exception cref="ArgumentOutOfRangeException">type - null</exception>
        public DataSourceXml(SettingsType type)
        {
            switch (type)
            {
            case SettingsType.DataTransfer:
                Settings = new XmlSerializerSettings()
                {
                    Indent = false, NullValueHandling = XmlNullValueHandling.Ignore, OmitXmlDeclaration = true
                };
                break;

            case SettingsType.ManualEditing:
                Settings = new XmlSerializerSettings()
                {
                    Indent = true, NullValueHandling = XmlNullValueHandling.Include, OmitXmlDeclaration = false
                };
                break;

            case SettingsType.Both:
                Settings = new XmlSerializerSettings()
                {
                    Indent = true, NullValueHandling = XmlNullValueHandling.Ignore, OmitXmlDeclaration = false
                };
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(type), type, null);
            }
        }
コード例 #2
0
        /// <summary>
        /// The actual implementation of the Matches method as required by the
        /// <code>NUnit.Framework.Contraints.Constrant</code> class.
        ///
        /// The actual Matches(Object) method simply calls through to this type
        /// specific method.
        /// </summary>
        /// <param name="actual_">The actual output of the XMlSerializer</param>
        /// <returns></returns>
        public bool Matches(T actual_)
        {
            var outputXml = new StringBuilder();
            var xmlWriter = XmlWriter.Create(outputXml, XmlSerializerSettings.GetDefaultWriterSettings());

            using (xmlWriter)
            {
                _serializer.Serialize(actual_, xmlWriter);
                xmlWriter.Close();
            }

            _actualXml = outputXml.ToString();
            if (_referenceXml.Equals(_actualXml))
            {
                return(true);
            }

            var error = new StringBuilder();

            error.AppendLine("XML Serialization was incorrect.");
            error.AppendLine("Expected: ");
            error.AppendLine(_referenceXml);
            error.AppendLine("Actual: ");
            error.AppendLine(_actualXml);
            _errorMessage = error.ToString();
            return(false);
        }
コード例 #3
0
        public static XmlSerializer CreateSerializer([NotNull] Type type, XmlSerializerSettings settings = null)
        {
            XmlSerializer serializer = __serializersCache.GetOrAdd(type, e => settings == null
                                                                                                                                                                ? __factory.Value.CreateSerializer(e)
                                                                                                                                                                : __factory.Value.CreateSerializer(e, settings.Overrides, settings.ExtraTypes, settings.Root, settings.DefaultNamespace, settings.Location));

            return(serializer ?? throw new SerializationException($"Could not create a serializer for the type {type.FullName}."));
        }
コード例 #4
0
        private XmlSerializer GetSerializer()
        {
            var settings = new XmlSerializerSettings
            {
                ContractResolver = new XmlContractResolver(NamingConventions.CamelCase)
            };

            return(new XmlSerializer(settings));
        }
コード例 #5
0
        public static IEnumerable <XmlConvertMethod> GetMethods(XmlSerializerSettings settings)
        {
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }

            throw new NotImplementedException();
        }
コード例 #6
0
        public static T Deserialize <T>(string value, XmlSerializerSettings settings = null, T defaultValue = default(T))
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                return(defaultValue);
            }
            XmlSerializer serializer = CreateSerializer(typeof(T), settings);

            return((T)Deserialize(value, serializer, (object)defaultValue));
        }
コード例 #7
0
        public static object Deserialize(string value, [NotNull] Type type, XmlSerializerSettings settings = null, object defaultValue = null)
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                return(defaultValue);
            }
            XmlSerializer serializer = CreateSerializer(type, settings);

            return(Deserialize(value, serializer, defaultValue));
        }
コード例 #8
0
        public static string Serialize <T>([NotNull] T value, XmlSerializerSettings settings = null, XmlWriterSettings writerSettings = null)
        {
            if (value.IsNull())
            {
                return(null);
            }
            XmlSerializer serializer = CreateSerializer <T>(settings);

            return(Serialize(value, serializer, writerSettings ?? XmlWriterHelper.CreateSettings()));
        }
コード例 #9
0
        public static string Serialize(object value, XmlSerializerSettings settings = null, XmlWriterSettings writerSettings = null)
        {
            if (value.IsNull())
            {
                return(null);
            }
            XmlSerializer serializer = CreateSerializer(value.GetType(), settings);

            return(Serialize(value, serializer, writerSettings ?? XmlWriterHelper.CreateSettings()));
        }
コード例 #10
0
        public static string Serialize(object entity, string rootElementName, XmlSerializerSettings settings)
        {
            XmlDataSerializer serializer = new XmlDataSerializer(settings);

            if (string.IsNullOrEmpty(rootElementName))
            {
                return(serializer.Serialize(entity));
            }
            else
            {
                return(serializer.Serialize(entity, rootElementName));
            }
        }
コード例 #11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="XmlFormatterOptions"/> class.
 /// </summary>
 /// <remarks>
 /// The following table shows the initial property values for an instance of <see cref="XmlFormatterOptions"/>.
 /// <list type="table">
 ///     <listheader>
 ///         <term>Property</term>
 ///         <description>Initial Value</description>
 ///     </listheader>
 ///     <item>
 ///         <term><see cref="Settings"/></term>
 ///         <description><see cref="XmlSerializerSettings"/></description>
 ///     </item>
 ///     <item>
 ///         <term><see cref="SynchronizeWithXmlConvert"/></term>
 ///         <description><c>true</c></description>
 ///     </item>
 ///     <item>
 ///         <term><see cref="IncludeExceptionStackTrace"/></term>
 ///         <description><c>false</c></description>
 ///     </item>
 /// </list>
 /// </remarks>
 public XmlFormatterOptions()
 {
     Settings = new XmlSerializerSettings();
     XmlSerializerSettings.DefaultConverters = list =>
     {
         list.AddExceptionDescriptorConverter();
         list.AddExceptionConverter(() => IncludeExceptionStackTrace);
         list.AddEnumerableConverter();
         list.AddUriConverter();
         list.AddDateTimeConverter();
         list.AddTimeSpanConverter();
         list.AddStringConverter();
     };
 }
コード例 #12
0
        public NetBikeXmlMediaTypeFormatter(XmlSerializerSettings settings)
        {
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }

            serializer = new XmlSerializer(settings);

            SupportedEncodings.Add(new UTF8Encoding(false, true));
            SupportedEncodings.Add(new UnicodeEncoding(false, true, true));

            SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml"));
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/xml"));
        }
コード例 #13
0
        public void WriteFooWithGlobalInlcludeNullHandlingTest()
        {
            var value = new Foo
            {
                Id   = 1,
                Name = null
            };

            var settings = new XmlSerializerSettings
            {
                OmitXmlDeclaration = true,
                NullValueHandling  = XmlNullValueHandling.Include,
                ContractResolver   = new XmlContractResolver(NamingConventions.CamelCase)
            };

            var actual   = GetConverter().ToXml(value, settings: settings);
            var expected = @"<xml><id>1</id><name p2:nil=""true"" xmlns:p2=""http://www.w3.org/2001/XMLSchema-instance"" /><reference p2:nil=""true"" xmlns:p2=""http://www.w3.org/2001/XMLSchema-instance"" /><enumValue p2:nil=""true"" xmlns:p2=""http://www.w3.org/2001/XMLSchema-instance"" /></xml>";

            Assert.That(actual, IsXml.Equals(expected).WithIgnore(XmlComparisonType.NamespacePrefix));
        }
コード例 #14
0
        /// <summary>
        /// Asigna la configuración de la instancia a crear.
        /// </summary>
        /// <param name="config">Instancia de la configuracion. Tiene que ser serializable en xml</param>
        /// <param name="rootName">Nombre a usar para el root de xml al serializar la configuración</param>
        public virtual void SetConfiguration(object config, string rootName)
        {
            XmlSerializerSettings set = new XmlSerializerSettings();

            set.UniqueSerializationForInstance = false;
            set.WriteRootTypeDefinition        = false;
            if (string.IsNullOrEmpty(rootName))
            {
                this.ComponentConfiguration = XmlHelper.Serialize(config, null, set);
            }
            else
            {
                this.ComponentConfiguration = XmlHelper.Serialize(config, rootName, set);
                _configuration = config;
            }

            if (config != null)
            {
                _configurationType = config.GetType();
            }
        }
コード例 #15
0
        private static XmlSerializationContext CreateContext(Type valueType, XmlMember member, XmlContract contract, XmlSerializerSettings settings)
        {
            if (settings == null)
            {
                settings = new XmlSerializerSettings
                {
                    OmitXmlDeclaration = true,
                    ContractResolver   = new XmlContractResolver(NamingConventions.CamelCase)
                };
            }

            if (contract == null)
            {
                contract = settings.ContractResolver.ResolveContract(valueType);
            }

            if (member == null)
            {
                member = contract.Root;
            }

            return(new XmlSerializationContext(settings, member, contract));
        }
コード例 #16
0
 /// <summary>
 /// Applies the specified <paramref name="settings"/> to the function delegate <see cref="XmlConvert.DefaultSettings"/>.
 /// </summary>
 /// <param name="settings">The XML serializer settings.</param>
 public static void ApplyToDefaultSettings(this XmlSerializerSettings settings)
 {
     XmlConvert.DefaultSettings = () => settings;
 }
コード例 #17
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DataSourceXml"/> class.
 /// </summary>
 /// <param name="settings">The settings.</param>
 /// <exception cref="ArgumentNullException">settings</exception>
 public DataSourceXml(XmlSerializerSettings settings)
 {
     Settings = settings ?? throw new ArgumentNullException(nameof(settings));
 }
コード例 #18
0
 public static TValue ParseXml <TValue>(this IXmlConverter converter, string xmlString, XmlMember member = null, XmlContract contract = null, XmlSerializerSettings settings = null)
 {
     return((TValue)ParseXml(converter, typeof(TValue), xmlString, member, contract, settings));
 }
コード例 #19
0
 public static string ToXml <TValue>(this IXmlConverter converter, TValue value, XmlMember member = null, XmlContract contract = null, XmlSerializerSettings settings = null)
 {
     return(ToXml(converter, typeof(TValue), value, member, contract, settings));
 }
コード例 #20
0
 public static XmlSerializer CreateSerializer <T>(XmlSerializerSettings settings = null)
 {
     return(CreateSerializer(typeof(T), settings));
 }
コード例 #21
0
        public static object ParseXml(this IXmlConverter converter, Type valueType, string xmlString, XmlMember member = null, XmlContract contract = null, XmlSerializerSettings settings = null)
        {
            var context = CreateContext(valueType, member, contract, settings);

            using (var input = new StringReader(xmlString))
                using (var reader = XmlReader.Create(input, context.Settings.GetReaderSettings()))
                {
                    while (reader.NodeType != XmlNodeType.Element && reader.Read())
                    {
                    }

                    if (reader.Name != "xml")
                    {
                        Assert.Fail("Expected start element \"xml\".");
                    }

                    var isAttribute = context.Member.MappingType == XmlMappingType.Attribute;

                    if (isAttribute)
                    {
                        reader.MoveToAttribute(context.Member.Name.LocalName, context.Member.Name.NamespaceUri);
                    }

                    var value = converter.ReadXml(reader, context);

                    if (isAttribute)
                    {
                        reader.MoveToElement();

                        if (reader.NodeType != XmlNodeType.Element || reader.Name != "xml")
                        {
                            Assert.Fail("Expected element \"xml\".");
                        }
                    }
                    else if (reader.NodeType != XmlNodeType.None)
                    {
                        Assert.Fail("Expected end of xml.");
                    }

                    return(value);
                }
        }
コード例 #22
0
        public static string ToXml(this IXmlConverter converter, Type valueType, object value, XmlMember member = null, XmlContract contract = null, XmlSerializerSettings settings = null)
        {
            var builder = new StringBuilder();
            var context = CreateContext(valueType, member, contract, settings);

            using (var output = new StringWriter(builder))
                using (var writer = XmlWriter.Create(output, context.Settings.GetWriterSettings()))
                {
                    writer.WriteStartElement("xml");

                    var isAttribute = context.Member.MappingType == XmlMappingType.Attribute;

                    if (isAttribute)
                    {
                        writer.WriteStartAttribute(context.Member.Name);
                    }

                    converter.WriteXml(writer, value, context);

                    if (isAttribute)
                    {
                        writer.WriteEndAttribute();
                    }

                    writer.WriteEndElement();
                }

            return(builder.ToString());
        }
コード例 #23
0
        public static TObj Deserialize <TObj>(string rootElementName, XmlReader reader, XmlSerializerSettings settings)
        {
            XmlDataSerializer serializer = new XmlDataSerializer(settings);

            return((TObj)serializer.Deserialize(typeof(TObj), rootElementName, reader));
        }
コード例 #24
0
        public static TObj Deserialize <TObj>(string rootElementName, string xmlObject, XmlSerializerSettings settings)
        {
            XmlDataSerializer serializer = new XmlDataSerializer(settings);

            return((TObj)serializer.Deserialize(typeof(TObj), rootElementName, xmlObject));
        }
コード例 #25
0
        public static TObj Deserialize <TObj>(string xml, XmlSerializerSettings settings)
        {
            XmlDataSerializer serializer = new XmlDataSerializer(settings);

            return((TObj)serializer.Deserialize(typeof(TObj), xml));
        }
コード例 #26
0
        public static object Deserialize(Type rootType, string rootElementName, string xmlObject, XmlSerializerSettings settings)
        {
            XmlDataSerializer serializer = new XmlDataSerializer(settings);

            return(serializer.Deserialize(rootType, rootElementName, xmlObject));
        }
コード例 #27
0
        public static object Deserialize(string xmlObject, XmlSerializerSettings settings)
        {
            XmlDataSerializer serializer = new XmlDataSerializer(settings);

            return(serializer.Deserialize(xmlObject));
        }