コード例 #1
0
        public void Verify()
        {
            const string content = @"<?xml version=""1.0"" encoding=""utf-8""?><Issue447Tests-Subject xmlns=""clr-namespace:ExtendedXmlSerializer.Tests.ReportedIssues;assembly=ExtendedXmlSerializer.Tests.ReportedIssues""><Message><![CDATA[Hello ]]><![CDATA[world!]]></Message><Message2><![CDATA[Not ]]><![CDATA[this.]]></Message2></Issue447Tests-Subject>";

            var serializer = new ConfigurationContainer().Create()
                             .ForTesting();

            serializer.Deserialize <Subject>(content)
            .Message.Should().Be("Hello world!");

            serializer.Deserialize <Subject>(content)
            .Message2.Should().Be("Not this.");
        }
コード例 #2
0
 public static Settings LoadSettings()
 {
     try
     {
         if (File.Exists(SettingsFileName))
         {
             using (XmlReader reader = XmlReader.Create(SettingsFileName))
             {
                 IExtendedXmlSerializer serializer = new ConfigurationContainer().Create();
                 return((Settings)serializer.Deserialize(reader));
             }
         }
         else
         {
             //creating example conf
             using (var writer = XmlWriter.Create(SettingsFileName, xmlWriterSettings))
             {
                 IExtendedXmlSerializer serializer = new ConfigurationContainer().Create();
                 Settings exampleSettings          = new Settings();
                 exampleSettings.initDefaultSettings();
                 serializer.Serialize(writer, exampleSettings);
                 writer.Flush();
             }
         }
     }
     catch (Exception e)
     {
         MainWindow.HandleError("Error during write file (stats.xml)", e, false);
     }
     return(null);
 }
コード例 #3
0
        void Verify()
        {
            var container = new ConfigurationContainer().EnableReaderContext()
                            .ConfigureType <Owner>()
                            .Member(x => x.Element)
                            .Register(typeof(Serializer))
                            .Create();

            var instance = new Owner
            {
                Element = new DatabaseObject {
                    Id = Guid.NewGuid(), Table = "TableName", Creted = "Loader"
                }
            };
            var content = container.Serialize(instance);
            var key     = new XmlReaderFactory().Get(new MemoryStream(Encoding.UTF8.GetBytes(content)));
            var owner   = Get(key);

            RestoreDatabaseObjects.Default.Execute(key);

            owner.ShouldBeEquivalentTo(instance);
            owner.Element.Table.Should()
            .Be("TableName");

            Owner Get(XmlReader reader)
            {
                using (reader)
                {
                    return((Owner)container.Deserialize(reader));
                }
            }
        }
コード例 #4
0
        public bool LoadSettings()
        {
            XmlSerializer formatter = new XmlSerializer(typeof(Setting));
            string        patch     = get_setting_file_patch();

            lock (syncLoadSet)
            {
                if (System.IO.File.Exists(patch))
                {
                    try
                    {
                        using (StreamReader writer = new StreamReader(get_setting_file_patch()))
                        {
                            IExtendedXmlSerializer serializer = new ConfigurationContainer().UseAutoFormatting()
                                                                .UseOptimizedNamespaces()
                                                                .EnableImplicitTyping(typeof(Setting))
                                                                .Create();
                            setting = serializer.Deserialize <Setting>(writer);
                        }
                    }
                    catch (Exception ex)
                    {
                        setting = new Setting();
                        Console.WriteLine("Error load setting: " + ex);
                    }
                }
                else
                {
                    setting = new Setting();
                }
            }
            return(true);
        }
コード例 #5
0
        public void TestInterceptor()
        {
            // language=XML
            const string xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
				<Issue451Tests_Reported-Processor>
				 <Enabled>true</Enabled>
				 <Filters>
				  <Filter>
				   <Type>ISO</Type>
				  </Filter>
				 </Filters>
				</Issue451Tests_Reported-Processor>"                ;

            var serializer = new ConfigurationContainer().EnableImplicitTyping(typeof(Processor))
                             .Type <Processor>()
                             .WithInterceptor(new Interceptor())
                             .Create();

            var contentStream = new MemoryStream(Encoding.UTF8.GetBytes(xml));

            using var reader = XmlReader.Create(contentStream);
            var processor = (Processor)serializer.Deserialize(reader);

            processor.Should().NotBeNull();
            processor.Enabled.Should().BeTrue();
            processor.Filters.Should().NotBeEmpty();
            processor.Filters.Only().Type.Should().Be("ISO");
        }
コード例 #6
0
        void Verify()
        {
            var support = new ConfigurationContainer().EnableImplicitTypingFromPublicNested <Issue206Tests>()
                          .EnableClassicListNaming()
                          .Create()
                          .ForTesting();

            var subject = new[] { new TravelFile {
                                      Name = "Hello World!", Participants = new[]
                                      {
                                          new Participant {
                                              ParticipantId = 679556, Name = "xxxx"
                                          },
                                          new Participant {
                                              ParticipantId = 679557, Name = "xxx"
                                          }
                                      }.ToList()
                                  } };

            support.Deserialize <TravelFile[]>(@"<?xml version=""1.0"" encoding=""utf-8""?><ArrayOfIssue206Tests-TravelFile xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" ><Issue206Tests-TravelFile Name=""Hello World!""><Participants>
		 <Issue206Tests-Participant>
			<ParticipantId>679556</ParticipantId>
			<Name>xxxx</Name>
		 </Issue206Tests-Participant>
		 <Issue206Tests-Participant>
			<ParticipantId>679557</ParticipantId>
			<Name>xxx</Name>
</Issue206Tests-Participant>
	  </Participants></Issue206Tests-TravelFile></ArrayOfIssue206Tests-TravelFile>"    )
            .ShouldBeEquivalentTo(subject);
        }
コード例 #7
0
        public T Deserialize <T>(string data)
        {
            IExtendedXmlSerializer serializer = new ConfigurationContainer()
                                                .Create();

            return(serializer.Deserialize <T>(data));
        }
コード例 #8
0
        void VerifyContinue()
        {
            var serializer = new ConfigurationContainer().EnableImplicitTyping(typeof(Entity), typeof(Entity2))
                             .WithUnknownContent()
                             .Continue()
                             .Create();

            // language=XML
            const string content1 =
                @"<?xml version=""1.0"" encoding=""utf-8""?>
				<Issue271Tests-Entity>
					<Name>Foo</Name>
					<Show>false</Show>
					<Children>
						<Issue271Tests-Entity>
							<Name>Bar</Name>
							<Show>false</Show>
						</Issue271Tests-Entity>
						<Issue271Tests-Entity>
							<Name>Jim</Name>
							<Show>true</Show>
						</Issue271Tests-Entity>
					</Children>
				</Issue271Tests-Entity>"                ;

            serializer.Deserialize <Entity>(content1)
            .Children.Should()
            .HaveCount(2);
        }
コード例 #9
0
        void Verify()
        {
            var serializer = new ConfigurationContainer()
                             .EnableImplicitTyping(typeof(MediaContainer), typeof(MediaItem))
                             .Create();

            var subject = new MediaContainer
            {
                Size  = 1,
                Items = new List <MediaItem>
                {
                    new MediaItem {
                        Id = "1", Name = "Name1"
                    }, new MediaItem {
                        Id = "2", Name = "Name2"
                    }
                }
            };
            // language=XML
            const string content =
                @"<?xml version=""1.0"" encoding=""utf-8""?>
<Issue243Tests-MediaContainer size=""1"">
	<MediaItem>
		<Issue243Tests-MediaItem Name=""Name1"" Id=""1"" />
		<Issue243Tests-MediaItem Name=""Name2"" Id=""2"" />
	</MediaItem>
</Issue243Tests-MediaContainer>";

            var result = serializer.Deserialize <MediaContainer>(content);

            result.ShouldBeEquivalentTo(subject);
            result.Items.Should()
            .HaveCount(2);
        }
コード例 #10
0
ファイル: XmlHelper.cs プロジェクト: wwkkww1983/SDDQ-dev
        /// <summary>
        /// 从XML字符串中反序列化对象
        /// </summary>
        /// <typeparam name="T">结果对象类型</typeparam>
        /// <param name="s">包含对象的XML字符串</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>反序列化得到的对象</returns>
        public static T XmlDeserialize <T>(string s, Encoding encoding)
        {
            if (string.IsNullOrEmpty(s))
            {
                throw new ArgumentNullException("s");
            }
            if (encoding == null)
            {
                throw new ArgumentNullException("encoding");
            }


            IExtendedXmlSerializer serializer = new ConfigurationContainer()
                                                .Type <T>()
                                                .EnableImplicitTyping(typeof(object))
                                                .UseOptimizedNamespaces()
                                                .Create();

            using (MemoryStream ms = new MemoryStream(encoding.GetBytes(s)))
            {
                using (StreamReader sr = new StreamReader(ms, encoding))
                {
                    return((T)serializer.Deserialize <T>(sr));
                }
            }
        }
コード例 #11
0
        void Verify()
        {
            const string content = @"<?xml version=""1.0"" encoding=""UTF-8""?>
<pin>
  <id>1309801580</id>
  <code>GBCT</code>
  <expires-at>2020-05-10T18:52:14Z</expires-at>
  <user-id>231221</user-id>
  <client-identifier>8c89f40c-e1f3-45e1-95bc-a45a047ce77f</client-identifier>
  <trusted>false</trusted>
  <auth-token>z6ZM5jeSP19WroEQc2Xy</auth-token>
  <auth_token>z6ZM5jeSP19WroEQc2Xy</auth_token>
</pin>";
            var          support = new ConfigurationContainer().EnableImplicitTyping(typeof(Pin))
                                   .WithUnknownContent()
                                   .Continue()
                                   .Create()
                                   .ForTesting();
            var stored = support.Deserialize <Pin>(content);

            var expectation = new Pin
            {
                ID           = 1309801580, Code = "GBCT",
                ExpiresAtUTC = DateTimeOffset.Parse("2020-05-10T18:52:14Z").UtcDateTime,
                AuthToken    = "z6ZM5jeSP19WroEQc2Xy", ClientIdentifier = new Guid("8c89f40c-e1f3-45e1-95bc-a45a047ce77f")
            };

            stored.Should().BeEquivalentTo(expectation);
        }
コード例 #12
0
        public void DictionaryAttributes()
        {
            var serializer = new ConfigurationContainer()
                             .Type <SimpleSubject>()
                             .Member(x => x.Number, x => x.Attribute())
                             .Create();

            var expected = new DictionaryWithProperties
            {
                { "First", 1 },
                { "Second", 2 },
                { "Other", 3 }
            };

            expected.Message = HelloWorld;
            expected.Number  = 6776;

            var data   = serializer.Serialize(expected);
            var actual = serializer.Deserialize <DictionaryWithProperties>(data);

            Assert.NotNull(actual);
            Assert.Equal(HelloWorld, actual.Message);
            Assert.Equal(6776, actual.Number);
            Assert.Equal(expected.Count, actual.Count);
            foreach (var entry in actual)
            {
                Assert.Equal(expected[entry.Key], entry.Value);
            }
        }
コード例 #13
0
        public void GenericDictionaryAttributes()
        {
            var serializer = new ConfigurationContainer()
                             .Type <GenericDictionaryWithProperties <int, string> >()
                             .Member(x => x.Message, x => x.Attribute())
                             .Member(x => x.Number, x => x.Attribute())
                             .Create();

            var expected = new GenericDictionaryWithProperties <int, string>
            {
                { 1, "First" },
                { 2, "Second" },
                { 3, "Other" }
            };

            expected.Message = HelloWorld;
            expected.Number  = 6776;

            var data   = serializer.Serialize(expected);
            var actual = serializer.Deserialize <GenericDictionaryWithProperties <int, string> >(data);

            Assert.NotNull(actual);
            Assert.Equal(HelloWorld, actual.Message);
            Assert.Equal(6776, actual.Number);
            Assert.Equal(expected.Count, actual.Count);
            foreach (var entry in actual)
            {
                Assert.Equal(expected[entry.Key], entry.Value);
            }
        }
コード例 #14
0
        public void Execute(object parameter)
        {
            Program.PrintHeader("Serialization with Settings Override");
// Serialization

            IExtendedXmlSerializer serializer = new ConfigurationContainer().Create();
            TestClass    instance             = new TestClass();
            MemoryStream stream = new MemoryStream();

            string contents = serializer.Serialize(new XmlWriterSettings {             /* ... */
            }, stream, instance);

// EndSerialization

            Console.WriteLine(contents);

            Program.PrintHeader("Deserialization with Settings Override");
// Deserialization

            MemoryStream contentStream = new MemoryStream(Encoding.UTF8.GetBytes(contents));
            TestClass    deserialized  = serializer.Deserialize <TestClass>(new XmlReaderSettings {       /* ... */
            }, contentStream);

// EndDeserialization
            Console.WriteLine($"Object id = {deserialized.Id}");
        }
コード例 #15
0
        public void Verify()
        {
            // language=XML
            const string input =
                @"<Zoo><Animals><Issue473Tests-Animal Name=""Hello""/><Human/><Issue473Tests-Animal Name=""World""/></Animals></Zoo>";

            var serializer = new ConfigurationContainer().Type <Zoo>()
                             .Name("Zoo")
                             .EnableImplicitTyping(typeof(Zoo), typeof(Animal))
                             .WithUnknownContent()
                             .Continue()
                             .Create();

            var contentStream = new MemoryStream(Encoding.UTF8.GetBytes(input));
            var reader        = XmlReader.Create(contentStream);
            var deserialized  = (Zoo)serializer.Deserialize(reader);

            deserialized.Animals.Count.Should().Be(2);

            var expected = new Zoo
            {
                Animals = new List <Animal> {
                    new Animal {
                        Name = "Hello"
                    }, new Animal {
                        Name = "World"
                    }
                }
            };

            deserialized.Should().BeEquivalentTo(expected);
        }
コード例 #16
0
ファイル: DictianarySamples.cs プロジェクト: wtf3505/home
        public static void Run()
        {
            Program.PrintHeader("Serialization");

            IExtendedXmlSerializer serializer = new ConfigurationContainer().Create();
// InitDictionary

            TestClass obj = new TestClass
            {
                Dictionary = new Dictionary <int, string>
                {
                    { 1, "First" },
                    { 2, "Second" },
                    { 3, "Other" },
                }
            };
// EndInitDictionary
            string xml = serializer.Serialize(new XmlWriterSettings {
                Indent = true
            }, obj);

            File.WriteAllText("bin\\DictianarySamples.xml", xml);
            Console.WriteLine(xml);

            Program.PrintHeader("Deserialization");
            serializer.Deserialize <TestClass>(xml);

            serializer = new ConfigurationContainer().UseOptimizedNamespaces().Create();
            xml        = serializer.Serialize(new XmlWriterSettings()
            {
                Indent = true
            }, obj);
            File.WriteAllText("bin\\DictianarySamplesUseOptimizedNamespaces.xml", xml);
        }
コード例 #17
0
 public static DepersonalizerProfile Load(string fileName)
 {
     using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
     {
         var serializer = new ConfigurationContainer().Create();
         return(serializer.Deserialize <DepersonalizerProfile>(stream));
     }
 }
コード例 #18
0
        public static void FromXML2 <T>(out T obj, string xml)
        {
            IExtendedXmlSerializer serializer = new ConfigurationContainer().Create();

            obj = serializer.Deserialize <T>(new XmlReaderSettings {
                IgnoreWhitespace = false
            }, xml);
        }
コード例 #19
0
        public void BasicArray()
        {
            var serializer = new ConfigurationContainer().EnableClassicMode().Create();
            var expected   = new[] { 1, 2, 3, 4, 5 };
            var data       = serializer.Serialize(expected);
            var actual     = serializer.Deserialize <int[]>(data);

            Assert.Equal(expected, actual);
        }
コード例 #20
0
        public void BasicHashSet()
        {
            var serializer = new ConfigurationContainer().EnableClassicMode().Create();
            var expected   = new HashSet <string> {
                "Hello", "World", "Hope", "This", "Works!"
            };
            var data   = serializer.Serialize(expected);
            var actual = serializer.Deserialize <HashSet <string> >(data);

            Assert.True(actual.SetEquals(expected));
        }
コード例 #21
0
        public void ShouldPreserveNullValueIfDefaultIsNotNull()
        {
            var serializer = new ConfigurationContainer().Emit(EmitBehaviors.Assigned).Create();

            var xml = serializer.Serialize(new ClassWithDefaultString {
                Name = null
            });
            var deserialized = serializer.Deserialize <ClassWithDefaultString>(xml);

            deserialized.Name.Should().BeNull();
        }
コード例 #22
0
        public void Test()
        {
            var serializer = new ConfigurationContainer().WithUnknownContent().Continue().Create();

            // Create an object which have its Id as element
            var obj2 = new RootObjectIdElement()
            {
                Id = 2, Name = "RootObjectId 2"
            };
            var text2 = serializer.Serialize(obj2);
            //_output.WriteLine(text2);
            // <?xml version="1.0" encoding="utf-8"?><BugAttributeInsteadOfElement-RootObjectIdElement xmlns="clr-namespace:Test.XmlSerializer;assembly=Test"><Id>2</Id><Name>RootObjectId 2</Name></BugAttributeInsteadOfElement-RootObjectIdElement>

            // TEST 1: Change object types which allows deserialize type
            var bugText1 = text2.Replace("RootObjectIdElement", "RootObjectIdAttribute");
            var bugObj1  = serializer.Deserialize <RootObjectIdAttribute>(bugText1);

            // RESULT 1: BUG encountered! Name is null although WithUnknownContent().Continue() is enabled
            bugObj1.Name.Should().Be("RootObjectId 2");
            bugObj1.Id.Should().Be(0);

            // TEST 2: Set Id as Attribute and parallel as unknown element
            var bugText2 = bugText1.Replace("-RootObjectIdAttribute ", @"-RootObjectIdAttribute Id=""1"" ");
            var bugObj2  = serializer.Deserialize <RootObjectIdAttribute>(bugText2);

            // RESULT 2: BUG also exists in case the attribute is set too
            bugObj2.Name.Should().Be("RootObjectId 2");
            bugObj2.Id.Should().Be(1);



            // TEST 3: Rename element Id to Id2 - therefore it has not the same name as expected attribute
            var bugText3 = bugText1.Replace("<Id>", "<Id2>").Replace("</Id>", "</Id2>");
            var bugObj3  = serializer.Deserialize <RootObjectIdAttribute>(bugText3);

            // RESULT 3: Works just fine
            bugObj3.Name.Should().NotBeNull();
            bugObj3.Id.Should().Be(0);

            // => BUG happens only if an unknown content is determined which has same name as an expected attribute!
        }
コード例 #23
0
        void VerifyProperty()
        {
            var container = new ConfigurationContainer().EnableImplicitTypingFromNested <Issue261Tests>()
                            .EnableClassicSchemaTyping()
                            .Create()
                            .ForTesting();

            const string content = @"<?xml version=""1.0"" encoding=""utf-8""?><Issue261Tests-Reference xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""><Association xsi:type=""Issue261Tests-Project"" /></Issue261Tests-Reference>";

            container.Deserialize <Reference>(content).Association.Should()
            .BeOfType <Project>();
        }
コード例 #24
0
        public void BasicList()
        {
            var serializer = new ConfigurationContainer().EnableClassicMode().Create();
            var expected   = new List <string> {
                "Hello", "World", "Hope", "This", "Works!"
            };
            var data   = serializer.Serialize(expected);
            var actual = serializer.Deserialize <List <string> >(data);

            actual.Capacity.Should().Be(8);
            Assert.Equal(expected, actual);
        }
コード例 #25
0
        public void NotAssigned()
        {
            var sut = new ConfigurationContainer().EnableParameterizedContent()
                      .Create()
                      .ForTesting();

            const string content = @"<?xml version=""1.0"" encoding=""utf-8""?><Issue143Tests-Subject Name=""Testing"" xmlns=""clr-namespace:ExtendedXmlSerializer.Tests.ReportedIssues;assembly=ExtendedXmlSerializer.Tests"" />";

            var subject = sut.Deserialize <Subject>(content);

            subject.Factor.Should().Be(.95);
        }
コード例 #26
0
        public void EmptyValueCount()
        {
            const string data =
                @"<?xml version=""1.0"" encoding=""utf-8""?><ImplicitlyDefinedDefaultValueAlterationTests-Person xmlns=""clr-namespace:ExtendedXmlSerializer.Tests.ExtensionModel.Content;assembly=ExtendedXmlSerializer.Tests""><FirstName>John</FirstName><LastName></LastName><Nationality>British</Nationality><Count/></ImplicitlyDefinedDefaultValueAlterationTests-Person>";

            var serializer = new ConfigurationContainer().EnableImplicitlyDefinedDefaultValues()
                             .ForTesting();

            var person = serializer.Deserialize <Person>(data);

            Assert.Equal(0, person.Count);
        }
コード例 #27
0
        public void Verify()
        {
            const string content = @"<Issue443Tests-TestRoot>
	<TestItems>
		<TestItem id=""TestItem1"" messageGroup=""Test"" messageNumber=""0x01"">
			<Notification>
				<StringFormat>
					Foo <Ref field=""Foo"" />
				</StringFormat>
			</Notification>
		</TestItem>
		<TestItem id=""TestItem2"" messageGroup=""Test"" messageNumber=""0x02"">
			<Command>
				<StringFormat>
					Foo <Ref field=""Foo"" />, Bar <Ref field=""Bar"" />, Baz <Ref field=""Baz"" />ms
				</StringFormat>
			</Command>

			<Response>
				<StringFormat>
					Foo <Ref field=""Foo"" />, Bar <Ref field=""Bar"" />
				</StringFormat>
			</Response>
		</TestItem>
		<TestItem id=""TestItem3"" messageGroup=""Test"" messageNumber=""0x03"">
			<Notification />
		</TestItem>

		<TestItem id=""TestItem4"" messageGroup=""Test"" messageNumber=""0x04"">
			<Notification />
		</TestItem>
	</TestItems>
</Issue443Tests-TestRoot>";

            var settings = new XmlReaderSettings
            {
                IgnoreWhitespace = false
            };
            var reader = XmlReader.Create(new StringReader(content), settings);

            var serializer = new ConfigurationContainer().EnableImplicitTyping(typeof(TestRoot))

                             /*.WithUnknownContent()
                              * .Throw()*/
                             .Type <MessageStringFormat>()
                             .Register()
                             .Serializer()
                             .Using(StringFormatSerializer.Default)
                             .Create();

            serializer.Deserialize(reader).AsValid <TestRoot>().TestItems.Should().HaveCount(4);
        }
コード例 #28
0
        public static CombatState DeserializeFromXml(string fileName)
        {
            // XML Serializer for the object
            var serializer = new ConfigurationContainer()
                             .EnableImplicitTypingFromNested <CombatState>()
                             .Create();

            // XML Reader
            using (var reader = new XmlTextReader(fileName))
            {
                // Deserialize
                return(serializer.Deserialize(reader) as CombatState);
            }
        }
コード例 #29
0
        public void Execute(object parameter)
        {
// Example
            string contents =
                @"<?xml version=""1.0"" encoding=""utf-8""?>
		<Subject xmlns=""clr-namespace:ExtendedXmlSerializer.Samples.Extensibility;assembly=ExtendedXmlSerializer.Samples""
		Message=""{Extension 'PRETTY COOL HUH!!!'}"" />"        ;
            IExtendedXmlSerializer serializer = new ConfigurationContainer().EnableMarkupExtensions()
                                                .Create();
            Subject subject = serializer.Deserialize <Subject>(contents);

            Console.WriteLine(subject.Message); // "Hello World from Markup Extension! Your message is: PRETTY COOL HUH!!!"
// EndExample
        }
コード例 #30
0
        public void VerifySingleton()
        {
            var serializer = new ConfigurationContainer().CustomSerializer <string, BasicCustomSerializerSingleton>()
                             .Create()
                             .ForTesting();

            var data = "<?xml version=\"1.0\" encoding=\"utf-8\"?><string xmlns=\"https://extendedxmlserializer.github.io/system\">Custom String!</string>";

            serializer.Assert("Subject String", data);

            serializer.Deserialize <string>(data)
            .Should()
            .Be("Hello world!");
        }