当前位置: 首页>>代码示例>>C#>>正文


C# XmlSerializer.Serialize方法代码示例

本文整理汇总了C#中System.Xml.Serialization.XmlSerializer.Serialize方法的典型用法代码示例。如果您正苦于以下问题:C# XmlSerializer.Serialize方法的具体用法?C# XmlSerializer.Serialize怎么用?C# XmlSerializer.Serialize使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Xml.Serialization.XmlSerializer的用法示例。


在下文中一共展示了XmlSerializer.Serialize方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: SendAsync

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var orderSerializer = new XmlSerializer(typeof(PurchaseOrderType));
            var ordersSerializer = new XmlSerializer(typeof(PurchaseOrdersType));

            var responseMessage = new HttpResponseMessage();
            var stream = new MemoryStream();
            var localPath = request.RequestUri.LocalPath;

            // GET /orders/notshipped
            if (localPath.EndsWith("/orders/notshipped"))
                ordersSerializer.Serialize(stream, repository.GetNotShipped());

            // GET /orders/shipped
            if (localPath.EndsWith("/orders/shipped"))
                ordersSerializer.Serialize(stream, repository.GetShipped());

            // POST /orders/{id}/ship
            if (localPath.EndsWith("/ship") && request.Method == HttpMethod.Post)
            {
                var shipUrl = localPath;
                var shipId = shipUrl.Replace("/api/orders/", string.Empty).Replace("/ship", string.Empty);
                var shipOrder = repository.Get(shipId);
                shipOrder.shipped = true;
                repository.Update(shipOrder);
            }

            // POST /orders
            if (localPath.EndsWith("/orders") && request.Method == HttpMethod.Post)
            {
                var result = request.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult();
                var xml = Encoding.UTF8.GetString(result);
                var newOrder = (PurchaseOrderType)orderSerializer.Deserialize(new StringReader(xml));
                repository.Add(newOrder);
            }

            // PUT /orders
            if (request.Method == HttpMethod.Put)
            {
                var result = request.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult();
                var xml = Encoding.UTF8.GetString(result);
                var orderToUpdate = (PurchaseOrderType)orderSerializer.Deserialize(new StringReader(xml));
                repository.Update(orderToUpdate);
            }

            if (request.Method == HttpMethod.Get && !localPath.EndsWith("/orders") && !localPath.EndsWith("/orders/") && !localPath.EndsWith("shipped"))
            {
                // GET /orders/{id}
                var url = localPath;
                var id = url.Replace("/api/orders/", string.Empty);
                var order = repository.Get(id);
                orderSerializer.Serialize(stream, order);
            }

            var content = Encoding.UTF8.GetString(stream.GetBuffer());
            content = content.Substring(content.IndexOf(Environment.NewLine) + 1);
            responseMessage.Content = new StringContent(content, Encoding.UTF8, "application/xml");

            return Task.FromResult(responseMessage);
        }
开发者ID:Gufalagupagup,项目名称:raml-dotnet-tools,代码行数:60,代码来源:FakeResponseHandler.cs

示例2: SessionInfoToString

        /// <summary>
        /// Sessions the info to string.
        /// </summary>
        /// <param name="sessionInfo">The session info.</param>
        /// <returns></returns>
        public static string SessionInfoToString(SessionInfo sessionInfo)
        {
            if (sessionInfo == null)
                return null;

            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);

            XmlSerializer xml = new XmlSerializer(typeof(SessionInfo));
            xml.Serialize(sw, sessionInfo);
            sw.Flush();

            CryptoString cry = new CryptoString(_key, CryptoString.Method.Encrypt, sb.ToString());
            string ret = cry.Execute();
            sb.Remove(0, sb.Length);
            if (Regex.IsMatch(ret, @".*[Oo][Nn][a-zA-Z]*=*$"))
            {
                sessionInfo.ConnectionString += ';';
                xml.Serialize(sw, sessionInfo);
                sw.Flush();
                cry = new CryptoString(_key, CryptoString.Method.Encrypt, sb.ToString());
                ret = cry.Execute();
            }

            sw.Close();
            return ret;
        }
开发者ID:Theeranit,项目名称:DealMarker,代码行数:32,代码来源:SessionInfoSerializer.cs

示例3: Main

        static void Main(string[] args)
        {
            Person p = new Person
            {
                FirstName = "Bart",
                MiddleName = "A",
                LastName = "Simpson"
            };

            XmlSerializer x = new XmlSerializer(p.GetType());
            x.Serialize(Console.Out, p);

            var outputFile = $"Person.xml";
            using (var fs = new FileStream(outputFile, FileMode.OpenOrCreate))
            {
                x.Serialize(fs, p);
            }
            using (var fs = new FileStream(outputFile, FileMode.OpenOrCreate))
            {
                var deserialize = (Person)x.Deserialize(fs);
            }

            Console.WriteLine();
            Console.ReadLine();
        }
开发者ID:CodeValue,项目名称:Advanced-Net-New-Employees-2016,代码行数:25,代码来源:Program.cs

示例4: ParseTracker

        public void ParseTracker()
        {
            var generator = new Generator();
            generator.Settings.ContextNaming = ContextNaming.Preserve;
            generator.Settings.EntityNaming = EntityNaming.Singular;
            generator.Settings.RelationshipNaming = RelationshipNaming.ListSuffix;
            generator.Settings.TableNaming = TableNaming.Singular;

            var selector = GetDatabaseSchema("Tracker");
            Assert.IsNotNull(selector);

            EntityContext entityContext = generator.Generate(selector);

            Assert.IsNotNull(entityContext);

            var settings = new XmlWriterSettings { Indent = true };
            var serializer = new XmlSerializer(typeof(EntityContext));

            using (var writer = XmlWriter.Create(@"..\..\Tracker.Generated.xml", settings))
                serializer.Serialize(writer, entityContext);

            string contextDirectory = @"..\..\..\Tracker.Core";
            string mappingDirectory = @"..\..\..\Tracker.Core\Mapping";

            Synchronizer.UpdateFromSource(entityContext, contextDirectory, mappingDirectory);

            using (var writer = XmlWriter.Create(@"..\..\Tracker.Updated.xml", settings))
                serializer.Serialize(writer, entityContext);
        }
开发者ID:loresoft,项目名称:PLINQO.EntityFramework.DbContext,代码行数:29,代码来源:ParserTest.cs

示例5: Write

 public static void Write(string file, Map overview)
 {
     if (string.IsNullOrEmpty(file))
         throw new Exception("File Not Empty");
     System.Xml.Serialization.XmlSerializer writer =
     new System.Xml.Serialization.XmlSerializer(typeof(Map));
     System.Xml.XmlWriterSettings setting = new System.Xml.XmlWriterSettings();
     setting.Encoding = Encoding.UTF8;
     setting.CloseOutput = true;
     setting.NewLineChars = "\r\n";
     setting.Indent = true;
     if (!File.Exists(file))
     {
         using (Stream s = File.Open(file, FileMode.OpenOrCreate))
         {
             System.Xml.XmlWriter tmp = System.Xml.XmlWriter.Create(s, setting);
             writer.Serialize(tmp, overview);
         }
     }
     else
     {
         using (Stream s = File.Open(file, FileMode.Truncate))
         {
             System.Xml.XmlWriter tmp = System.Xml.XmlWriter.Create(s, setting);
             writer.Serialize(tmp, overview);
         }
     }
 }
开发者ID:iceriver102,项目名称:alta-mtc-version-2,代码行数:28,代码来源:Map.cs

示例6: Can_serialize_object

		public void Can_serialize_object()
		{
			var testObject = GetTestObject();
			var xmlSerializer = new XmlSerializer<TestObject>();
			Assert.DoesNotThrow(() =>xmlSerializer.Serialize(testObject));
			var xPathNavigable = xmlSerializer.Serialize(testObject) as XmlDocument;
			Assert.That(xPathNavigable, Is.Not.Null);
		}
开发者ID:tonyto,项目名称:SevenDigital.Api.Wrapper,代码行数:8,代码来源:SerializationTests.cs

示例7: Test

		public void Test()
		{
			var serializer = new XmlSerializer(typeof(Quiz));
			var quiz = new Quiz
			{
				Title = "Title",
				Id = "Id",
				Blocks = new SlideBlock[]
				{
					new MdBlock {Markdown = "This is quiz!"},
					new IsTrueBlock
					{
						Id = "1",
						Text = "Это утверждение ложно",
					},
					new ChoiceBlock
					{
						Text = "What is the \nbest color?",
						Items = new[]
						{
							new ChoiceItem {Id="1", Description = "black", IsCorrect = true},
							new ChoiceItem {Id="2", Description = "green"},
							new ChoiceItem {Id="3", Description = "red"},
						}
					},
					new ChoiceBlock
					{
						Multiple = true,
						Text = "What does the fox say?",
						Items = new[]
						{
							new ChoiceItem {Description = "Apapapapa", IsCorrect = true},
							new ChoiceItem {Description = "Ding ding ding", IsCorrect = true},
							new ChoiceItem {Description = "Mew"},
						}
					},
					new FillInBlock
					{
						Text = "What does the fox say?",
						Regexes = new[] {new RegexInfo {Pattern = "([Dd]ing )+"}, new RegexInfo {Pattern = "Ap(ap)+"}},
						Sample = "Apapap"
					},
				}
			};
			var w1 = new StringWriter();
			var ns = new XmlSerializerNamespaces();
			ns.Add("x", "http://www.w3.org/2001/XMLSchema-instance");
			serializer.Serialize(w1, quiz, ns);
			ApprovalTests.Approvals.Verify(w1.ToString());
			Console.WriteLine(w1.ToString());
			Console.WriteLine();
			var quiz2 = serializer.Deserialize(new StringReader(w1.ToString()));
			var w2 = new StringWriter();
			serializer.Serialize(w2, quiz2, ns);
			Console.WriteLine(w2.ToString());
			Assert.AreEqual(w1.ToString(), w2.ToString());
		}
开发者ID:andgein,项目名称:uLearn,代码行数:57,代码来源:Quiz_Test.cs

示例8: UpdateManufacturingSpec

        public void UpdateManufacturingSpec()
        {
            // [1] check xml exists
            // [2] deserialize xml file to a manufacturingDetail object
            // [3] update manufacturingDetail object with ManufacturingParamters objects
            // [4] serialize manufacturingDetail object
            char[] charsToTrim = { '{', '}' };
            string fileName = this.GUID.Trim(charsToTrim) + ".xml";

            if (!File.Exists(Location))
            {
                Trace.TraceError("Error: " + Location + " not found!");
                return;
            }

            if (!Directory.Exists(this.NewLocation))
                Directory.CreateDirectory(this.NewLocation);

            if (ManufacturingParamters.Count() > 0)             // update xml
            {
                XmlSerializer mfgDetails_Serializer = new XmlSerializer(typeof(Part.manufacturingDetails));
                Part.manufacturingDetails mfdetail = Part.manufacturingDetails.Deserialize(Location);
                StringWriter sw = new StringWriter();
                sw.NewLine = "";
                mfgDetails_Serializer.Serialize(sw, mfdetail);
                string xmldatastring = sw.ToString();

                try
                {
                    foreach (KeyValuePair<string, string> item in ManufacturingParamters)
                    {
                        xmldatastring = ReplaceParameters(item.Key, item.Value, xmldatastring);
                    }

                    var strreader = new StringReader(xmldatastring);
                    Part.manufacturingDetails mfdetails_revised = (Part.manufacturingDetails)mfgDetails_Serializer.Deserialize(strreader);

                    if (!Directory.Exists(this.NewLocation))
                        Directory.CreateDirectory(this.NewLocation);
                    StreamWriter myWriter = new StreamWriter(Path.Combine(this.NewLocation, fileName));
                    mfgDetails_Serializer.Serialize(myWriter, mfdetails_revised);


                    Trace.TraceInformation("Info: Updated manufacturing xml with manufacturing parameter from model. " + this.NewLocation + "\\" + fileName);
                }
                catch (System.InvalidOperationException ex)
                {
                    Console.WriteLine("Exception occured: {0}", ex.ToString());
                }

            }
            else                                   // copy the xml
            {
                File.Copy(Location, Path.Combine(this.NewLocation, fileName), true);
                Trace.TraceInformation("Info: Copied manufacturing xml. " + this.NewLocation + "\\" + fileName);
            }
        }
开发者ID:neemask,项目名称:meta-core,代码行数:57,代码来源:ManufacturingData.cs

示例9: FolderPollInitTest

        public void FolderPollInitTest()
        {
            FolderPollConfig testConfig = new FolderPollConfig
            {
                Poll = new Poll[]
                {
                    new Poll
                    {
                        Domain = "domain",
                        Folder = @"C:\FolderPoll",
                        Impersonation = true,
                        Username = "username",
                        Password = "password",
                        NewFile = new NewFile
                        {
                            Filter = "*.txt",
                            Copy = new NewFileCopy
                            {
                                TargetFolder = @"C:\FolderPoll"
                            },
                            Move = new NewFileMove
                            {
                                TargetFolder = @"C:\FolderPoll"
                            },
                            Launch = new NewFileLaunch
                            {
                                Application = @"C:\Windows\notepad.exe",
                                Arguments = "{0}"
                            }
                        }
                    }
                }
            };

            var serializer = new XmlSerializer(typeof(FolderPollConfig));
            TextWriter streamWriter = new StreamWriter(@"C:\FolderPoll\testConfig.xml");
            serializer.Serialize(streamWriter, testConfig);
            streamWriter.Close();

            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add(string.Empty, string.Empty);
            StringWriter stringWriter = new StringWriter();
            serializer.Serialize(stringWriter, testConfig, ns);
            stringWriter.GetStringBuilder().ToString();

            var fileInitObject = new FolderPollService();
            fileInitObject.Init(@"C:\FolderPoll\testConfig.xml", true);
            var stringInitObject = new FolderPollService();
            stringInitObject.Init(stringWriter.GetStringBuilder().ToString(), false);

            var privateFileInit = new PrivateObject(fileInitObject);
            var privateStringInit = new PrivateObject(stringInitObject);

            Assert.IsNotNull(privateFileInit.GetField("folderPoll"));
            Assert.IsNotNull(privateStringInit.GetField("folderPoll"));
        }
开发者ID:nickvil,项目名称:FolderPoll,代码行数:56,代码来源:source1.cs

示例10: WriteXml

        public void WriteXml(XmlWriter writer)
        {
            XmlSerializer strSerializer = new XmlSerializer(typeof(string));
            XmlSerializer epcSerializer = new XmlSerializer(typeof(EffectParamCategory));
            Type paramType = Type.GetType(ValueTypeFullName);
            XmlSerializer objSerializer = new XmlSerializer(paramType);

            strSerializer.Serialize(writer, Name);
            epcSerializer.Serialize(writer, Category);
            strSerializer.Serialize(writer, ValueTypeFullName);
            objSerializer.Serialize(writer, Value);
        }
开发者ID:Tengato,项目名称:Mechadrone1,代码行数:12,代码来源:MaterialData.cs

示例11: Main

        public static void Main(string[] args)
        {
            // If initial value is the same as DefaultValueAttribute for variable declaration, 
            // it is not persisted by XmlSerializer.
            Clue clue = new Clue();
            clue.text = "Nothing To See Here";

            // Buffer for writing.
            StringBuilder buffer = new StringBuilder();

            // Don't need namespaces.
            XmlSerializerNamespaces no_namespaces = new XmlSerializerNamespaces();
            no_namespaces.Add(string.Empty, string.Empty);

            // Don't need xml declaration.
            XmlWriterSettings writer_settings = new XmlWriterSettings() { OmitXmlDeclaration = true };

            // Serialise the clue...
            XmlSerializer xml_serializer = new XmlSerializer(typeof(Clue));
            StringWriter string_writer = new StringWriter(buffer);
            using (XmlWriter xml_writer = XmlWriter.Create(string_writer, writer_settings))
            {
                xml_serializer.Serialize(xml_writer, clue, no_namespaces);
            }

            string serialized = buffer.ToString();

            // Show serialised version of the clue...
            Console.WriteLine("Clue text value: {0}", clue.text);
            Console.WriteLine("Clue serialized: {0}", serialized);

            // Deserialise the clue...
            Clue clue_read;
            using (StringReader sr = new StringReader(serialized))
            {
                clue_read = (Clue)xml_serializer.Deserialize(sr);
            }

            // Show clue 2 on console
            // Reset and reuse write buffer.
            buffer.Length = 0;
            using (XmlWriter xml_writer = XmlWriter.Create(string_writer, writer_settings))
            {
                xml_serializer.Serialize(xml_writer, clue_read, no_namespaces);
            }

            string reserialized = buffer.ToString();
            Console.WriteLine("Read Clue text value: {0}", clue_read.text);
            Console.WriteLine("Read Clue serialized: {0}", reserialized);

            Debug.Assert(clue.text == clue_read.text, "Written & read clue's text should match");
        }
开发者ID:paulecoyote,项目名称:blog,代码行数:52,代码来源:Demo.cs

示例12: SerializationTest

        private static void SerializationTest()
        {
            Person p1 = new Person() { Name = "Person 1", Age = 20 };
            Person p2 = new Person() { Name = "Person 2", Age = 60 };

            XmlSerializer serializer = new XmlSerializer(typeof(Person));
            serializer.Serialize(Console.OpenStandardOutput(), p1);

            Console.WriteLine();
            Console.WriteLine();

            serializer.Serialize(Console.OpenStandardOutput(), p2);
        }
开发者ID:GrahamClark,项目名称:TestConsoleApp,代码行数:13,代码来源:Runner.cs

示例13: XmlSerializer

 void IXmlSerializable.WriteXml(XmlWriter writer)
 {
     XmlSerializer ss = new XmlSerializer(typeof(string));
     writer.WriteStartElement("name");
     ss.Serialize(writer, Name);
     writer.WriteEndElement();
     writer.WriteStartElement("type");
     ss.Serialize(writer, Value.GetType().AssemblyQualifiedName);
     writer.WriteEndElement();
     writer.WriteStartElement("value");
     new XmlSerializer(Value.GetType()).Serialize(writer, Value);
     writer.WriteEndElement();
 }
开发者ID:burstinair,项目名称:burst.net,代码行数:13,代码来源:NameValue.cs

示例14: Main

 static void Main()
 {
     bool groups_directory_exist = false;
     bool subjects_directory_exist = false;
     DirectoryInfo current_dir_info = new DirectoryInfo(Environment.CurrentDirectory);
     foreach (DirectoryInfo cur_dir_info in current_dir_info.GetDirectories())
     {
         if (cur_dir_info.Name == "all_subjects")
         {
             subjects_directory_exist = true;
         }
         if (cur_dir_info.Name == "all_groups")
         {
             groups_directory_exist = true;
         }
     }
     if (!subjects_directory_exist)
     {
         List<subject> test_list_of_subjects = new List<subject>();
         test_list_of_subjects.Add(new subject("mathematics", new List<string> { "math_theme_1", "math_theme_2", "math_theme_3" }));
         test_list_of_subjects.Add(new subject("physics", new List<string> { "phys_theme_1", "phys_theme_2", "phys_theme_3" }));
         test_list_of_subjects.Add(new subject("biology", new List<string> { "bio_theme_1", "bio_theme_2", "bio_theme_3" }));
         Directory.CreateDirectory("all_subjects");
         XmlSerializer serializer_for_subjects = new XmlSerializer(typeof(List<subject>));
         FileStream stream_to_subjects = new FileStream(@"all_subjects\all_subjects.xml",
              FileMode.Create, FileAccess.Write);
         serializer_for_subjects.Serialize(stream_to_subjects, test_list_of_subjects);
         stream_to_subjects.Close();
     }
     if (!groups_directory_exist)
     {
         group test_group = new group("TEST_GROUP_1", new List<student> {new student("first_student_1"),
            new student("second_student_1"),new student("third_student_1")});
         group test_group_2 = new group("TEST_GROUP_2", new List<student> {new student("first_student_2"),
            new student("second_student_2"),new student("third_student_2")});
         Directory.CreateDirectory(@"all_groups\" + test_group.name_of_group + @"\all_lessons");
         Directory.CreateDirectory(@"all_groups\" + test_group_2.name_of_group + @"\all_lessons");
         FileStream stream_to_groups = new FileStream(@"all_groups\" + test_group.name_of_group +
             @"\" + test_group.name_of_group + ".xml", FileMode.Create, FileAccess.Write);
         XmlSerializer serializer_for_groups = new XmlSerializer(typeof(group));
         serializer_for_groups.Serialize(stream_to_groups, test_group);
         stream_to_groups.Close();
         FileStream stream_to_groups_2 = new FileStream(@"all_groups\" + test_group_2.name_of_group +
             @"\" + test_group_2.name_of_group + ".xml", FileMode.Create, FileAccess.Write);
         serializer_for_groups.Serialize(stream_to_groups_2, test_group_2);
         stream_to_groups_2.Close();
     }
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     Application.Run(new Form1());
 }
开发者ID:Saroko-dnd,项目名称:My_DZ,代码行数:51,代码来源:Program.cs

示例15: ConvertObjectToXml

        private static void ConvertObjectToXml(PhoneBook phoneBook)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(PhoneBook)); // it's better to use Form.GetType() for generics

            // save to file on the hard drive
            StreamWriter streamWriter = new StreamWriter("XML/PhoneBookRecreated.xml");
            xmlSerializer.Serialize(streamWriter, phoneBook);

            // example how to convert to string, instead of file (for debug purposes)
            using (StringWriter stringWriter = new StringWriter())
            {
                xmlSerializer.Serialize(stringWriter, phoneBook);
                string s = stringWriter.ToString();
            }
        }
开发者ID:sergeklokov,项目名称:ConvertXmlObjectWithSerialization,代码行数:15,代码来源:Program.cs


注:本文中的System.Xml.Serialization.XmlSerializer.Serialize方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。