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


C# Serialization.XmlSerializer类代码示例

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


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

示例1: ExistingFeatureInModelIsNotDuplicated

 public void ExistingFeatureInModelIsNotDuplicated()
 {
     var simpleScript =
         @"// Fills in details for download packages automatically.
         // This instance created AUTOMATICALLY during a previous run.
         function AutomatePackages()
         {
             SetElement(""FlavorName1"", ""NAME"");
             SetElement(""FlavorUrl1"", ""URL"");
             NextStage();
             NextStage();
         }";
     var configuration = new ConfigurationModel();
     configuration.Flavors = new List<ConfigurationModel.FlavorOptions> { new ConfigurationModel.FlavorOptions { FlavorName = "NAME"}};
     var scriptFile = Path.Combine(TestFolder, "test.js");
     var installerFile = Path.Combine(TestFolder, "installer.xml");
     File.WriteAllText(scriptFile, simpleScript);
     configuration.FileLocation = installerFile;
     configuration.Save();
     JavaScriptConverter.ConvertJsToXml(scriptFile, installerFile);
     var serializer = new XmlSerializer(typeof(ConfigurationModel));
     using (var textReader = new StreamReader(installerFile))
     {
         var model = (ConfigurationModel)serializer.Deserialize(textReader);
         Assert.That(model.Flavors, Is.Not.Null);
         Assert.That(model.Flavors.Count, Is.EqualTo(1));
         Assert.That(model.Flavors.First().FlavorName, Is.EqualTo("NAME"));
         Assert.That(model.Flavors.First().DownloadURL, Is.EqualTo("URL"));
     }
 }
开发者ID:sillsdev,项目名称:masterinstaller,代码行数:30,代码来源:JavaScriptConverterTests.cs

示例2: SendFileInfo

        public static void SendFileInfo()
        {

            // Получаем тип и расширение файла
            fileDet.FILETYPE = fs.Name.Substring((int)fs.Name.Length - 3, 3);

            // Получаем длину файла
            fileDet.FILESIZE = fs.Length;

            XmlSerializer fileSerializer = new XmlSerializer(typeof(FileDetails));
            MemoryStream stream = new MemoryStream();

            // Сериализуем объект
            fileSerializer.Serialize(stream, fileDet);

            // Считываем поток в байты
            stream.Position = 0;
            Byte[] bytes = new Byte[stream.Length];
            stream.Read(bytes, 0, Convert.ToInt32(stream.Length));

            Console.WriteLine("Отправка деталей файла...");

            // Отправляем информацию о файле
            sender.Send(bytes, bytes.Length, endPoint);
            stream.Close();

        }
开发者ID:Pashahasband,项目名称:SpaceKurs,代码行数:27,代码来源:Program.cs

示例3: DeserializeObjectAudioTrack

        public static BackgroundTrackItem DeserializeObjectAudioTrack(this string s)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(BackgroundTrackItem));
            StringReader textReader = new StringReader(s);

            return xmlSerializer.Deserialize(textReader) as BackgroundTrackItem;
        }
开发者ID:robUx4,项目名称:vlc-winrt,代码行数:7,代码来源:BackgroundAudioInterface.cs

示例4: LoadSettings

        public static MachineCollection LoadSettings(string path)
        {
            MachineCollection machineCollection;

            if (File.Exists(path))
            {
                XmlSerializer deserializer = new XmlSerializer(typeof(MachineCollection));
                using (TextReader textReader = new StreamReader(path))
                {
                    try
                    {
                        machineCollection = (MachineCollection)deserializer.Deserialize(textReader);
                        machineCollection.Initialize();
                    }
                    catch (System.Exception ex)
                    {
                        machineCollection = new MachineCollection();
                        Log.LogError("", ex);
                    }
                }
            }
            else
            {
                machineCollection = new MachineCollection();
            }
            return machineCollection;
        }
开发者ID:PosauneMaster,项目名称:RecipeMaster_v3,代码行数:27,代码来源:MachineCollection.cs

示例5: Serialize

 public static string Serialize(MaterialList mats)
 {
     StringWriter sw = new StringWriter();
     XmlSerializer ser = new XmlSerializer(typeof(MaterialList));
     ser.Serialize(sw, mats);
     return sw.ToString();
 }
开发者ID:BGCX261,项目名称:zjzl-svn-to-git,代码行数:7,代码来源:MaterialList.cs

示例6: Convert

        public void Convert(string inputFileName, string outputFileName)
        {
            var deser = new XmlSerializer(typeof(Song));
            Song zigSong;
            using (FileStream stream = new FileStream(inputFileName, FileMode.Open))
            {
                zigSong = (Song)deser.Deserialize(stream);
            }

            var guitarTrack = GetTrack(zigSong);
            if (guitarTrack == null)
            {
                throw new Exception("Couldn't find a guitar track");
            }

            var rsSong = new RsSong();
            AddSongMetadata(rsSong, zigSong);
            AddEbeats(rsSong, zigSong);
            AddNotes(rsSong, zigSong);

            deser = new XmlSerializer(typeof(RsSong));
            using (FileStream stream = new FileStream(outputFileName, FileMode.Create))
            {
                deser.Serialize(stream, rsSong);
            }
        }
开发者ID:Jamedjo,项目名称:rocksmith-custom-song-toolkit,代码行数:26,代码来源:Converter.cs

示例7: GetData

        private IEnumerable<ICompletionData> GetData(string highlightingName)
        {
            try
            {

            var result = new List<ICompletionData>();
            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Intellisense", "Keywords", "options.xml");
            using (var sr = new StreamReader(path))
            {
                var ser = new XmlSerializer(typeof(List<KeywordsFileOption>));
                var ops = (List<KeywordsFileOption>)ser.Deserialize(sr);

                var filePath = Path.Combine(Application.StartupPath, "Intellisense", "Keywords",
                    ops
                    .Where(x => string.Compare(x.HighlightingName, highlightingName) == 0)
                    .Select(x => x.Filename)
                    .FirstOrDefault() ?? string.Empty);
                if (File.Exists(filePath))
                {
                    var w = GetWords(filePath);
                    result.AddRange(w);
                }
            }
            return result;
            }
            catch (Exception)
            {
                // TODO: приделать логирование
                return new List<ICompletionData>();
            }
        }
开发者ID:tym32167,项目名称:dotnetnotepad,代码行数:31,代码来源:FileCompletionDataProvider.cs

示例8: LoadStateFromFile

        public static PersistentVM LoadStateFromFile(string filePath)
        {
            if (!File.Exists(filePath))
            {
                throw new ArgumentException(Resources.MissingPersistentVMFile, "filePath");
            }

            XmlAttributeOverrides overrides = new XmlAttributeOverrides();
            XmlAttributes ignoreAttrib = new XmlAttributes();
            ignoreAttrib.XmlIgnore = true;
            overrides.Add(typeof(DataVirtualHardDisk), "MediaLink", ignoreAttrib);
            overrides.Add(typeof(DataVirtualHardDisk), "SourceMediaLink", ignoreAttrib);
            overrides.Add(typeof(OSVirtualHardDisk), "MediaLink", ignoreAttrib);
            overrides.Add(typeof(OSVirtualHardDisk), "SourceImageName", ignoreAttrib);

            var serializer = new System.Xml.Serialization.XmlSerializer(typeof(PersistentVM), overrides, new Type[] { typeof(NetworkConfigurationSet) }, null, null);

            PersistentVM role = null;
            
            using (var stream = new FileStream(filePath, FileMode.Open))
            {
                role = serializer.Deserialize(stream) as PersistentVM;
            }

            return role;
        }
开发者ID:shuainie,项目名称:azure-powershell,代码行数:26,代码来源:PersistentVMHelper.cs

示例9: LoadResourceXml

		public LoadResourceXml ()
		{
			#region How to load an XML file embedded resource
			var assembly = typeof(LoadResourceText).GetTypeInfo().Assembly;
			Stream stream = assembly.GetManifestResourceStream("WorkingWithFiles.PCLXmlResource.xml");

			List<Monkey> monkeys;
			using (var reader = new System.IO.StreamReader (stream)) {
				var serializer = new XmlSerializer(typeof(List<Monkey>));
				monkeys = (List<Monkey>)serializer.Deserialize(reader);
			}
			#endregion

			var listView = new ListView ();
			listView.ItemsSource = monkeys;


			Content = new StackLayout {
				Padding = new Thickness (0, 20, 0, 0),
				VerticalOptions = LayoutOptions.StartAndExpand,
				Children = {
					new Label { Text = "Embedded Resource XML File (PCL)", 
						FontSize = Device.GetNamedSize (NamedSize.Medium, typeof(Label)),
						FontAttributes = FontAttributes.Bold
					}, listView
				}
			};

			// NOTE: use for debugging, not in released app code!
			//foreach (var res in assembly.GetManifestResourceNames()) 
			//	System.Diagnostics.Debug.WriteLine("found resource: " + res);
		}
开发者ID:ChandrakanthBCK,项目名称:xamarin-forms-samples,代码行数:32,代码来源:LoadResourceXml.cs

示例10: SaveToDataStore

        public override void SaveToDataStore(BlogEngine.Core.DataStore.ExtensionType exType, string exId, object settings)
        {
            XmlSerializer xs = new XmlSerializer(settings.GetType());
            string objectXML = string.Empty;
            using (StringWriter sw = new StringWriter())
            {
                xs.Serialize(sw, settings);
                objectXML = sw.ToString();
            }

            using (var mongo = new MongoDbWr())
            {
                var coll = mongo.BlogDB.GetCollection("DataStoreSettings");

                Document spec = new Document();
                spec["ExtensionType"] = exType;
                spec["ExtensionId"] = exId;

                var res = new Document();
                res["Settings"] = objectXML;
                res["ExtensionType"] = exType;
                res["ExtensionId"] = exId;

                coll.Update(res, spec, UpdateFlags.Upsert);
            }
        }
开发者ID:tikalk,项目名称:fuse.dotnet.mongodb-blogengine,代码行数:26,代码来源:DataStore.cs

示例11: When_reading_from_example_file_namespaces

        public When_reading_from_example_file_namespaces()
        {
            var readAllText = File.OpenRead(Path.Combine(Environment.CurrentDirectory, "..\\..\\..\\ExamplesFiles\\namespaces.xml"));

            var xmlSerializer = new XmlSerializer(typeof(root));
            root = (root)xmlSerializer.Deserialize(readAllText);
        }
开发者ID:ststeiger,项目名称:XmlToCSharp,代码行数:7,代码来源:When_reading_from_example_file_namespaces.cs

示例12: Save

        public bool Save()
        {
            IAmazonResponse amazonResponse = amazonFactory.GetResponse();

            XmlSerializer serializer;
            TextWriter writer;

            try
            {
                if (amazonResponse.Errors.Count != 0)
                {
                    serializer = new XmlSerializer(typeof (List<string>));
                    writer = new StreamWriter(fileParameters.ErrorFileNameAndPath);
                    serializer.Serialize(writer, amazonResponse.Errors);
                    writer.Close();
                }

                serializer = new XmlSerializer(typeof (List<Review>));
                writer = new StreamWriter(fileParameters.ReviewFileNameAndPath);
                serializer.Serialize(writer, amazonResponse.Reviews);
                writer.Close();

                serializer = new XmlSerializer(typeof (List<Product>));
                writer = new StreamWriter(fileParameters.ProductFileNameAndPath);
                serializer.Serialize(writer, amazonResponse.Products);
                writer.Close();
            }
            catch
            {
                return false;
            }
            return true;
        }
开发者ID:AdamDotCom,项目名称:adamdotcom-amazon,代码行数:33,代码来源:AmazonApplication.cs

示例13: Convert

        public void Convert(string inputFileName, string outputFileName)
        {
            var deser = new XmlSerializer(typeof(ZpeSong));
            ZpeSong zigSong;
            using (FileStream stream = new FileStream(inputFileName, FileMode.Open))
            {
                zigSong = (ZpeSong)deser.Deserialize(stream);
            }

            if (zigSong.PueVersion != 46)
                throw new Exception("Incompatable version of Ziggy Pro Editor XML");
            
            var guitarTrack = GetTrack(zigSong);
            if (guitarTrack == null)
            {
                throw new Exception("Couldn't find a guitar track");
            }

            var rsSong = new Song();
            AddSongMetadata(rsSong, zigSong);
            AddEbeats(rsSong, zigSong);
            AddNotes(rsSong, zigSong);

            using (FileStream stream = new FileStream(outputFileName, FileMode.Create))
            {
                rsSong.Serialize(stream, true);
            }
        }
开发者ID:aequitas,项目名称:rocksmith-custom-song-toolkit,代码行数:28,代码来源:Converter.cs

示例14: Deserialize

        public void Deserialize(string settingsPath)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Settings));
            TextReader reader = null;
            Settings settings = null;
            try
            {
                reader = new StreamReader(settingsPath + "\\" + FILE_NAME);
                settings = (Settings)serializer.Deserialize(reader);
            }
            catch {;}
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }                
            }            

            if (settings != null)
            {
                this.DeviceLogging = settings.DeviceLogging;
                this.DesktopLogging = settings.DesktopLogging;
                this.CommLogging = settings.CommLogging;
            }            
        }
开发者ID:Zeiren92,项目名称:bthmsdevemul,代码行数:26,代码来源:Settings.cs

示例15: ReadAllUseBasePath

		/// <summary>
		/// Reads in a file containing a map of saved discovery documents populating the Documents and References properties, 
		/// with discovery documents, XML Schema Definition (XSD) schemas, and service descriptions referenced in the file.
		/// </summary>
		/// <param name="topLevelFilename">Name of file to read in, containing the map of saved discovery documents.</param>
		/// <returns>
		/// A DiscoveryClientResultCollection containing the results found in the file with the map of saved discovery documents. 
		/// The file format is a DiscoveryClientProtocol.DiscoveryClientResultsFile class serialized into XML; however, one would 
		/// typically create the file using only the WriteAll method or Disco.exe.
		/// </returns>
		public DiscoveryClientResultCollection ReadAllUseBasePath(string topLevelFilename)
		{
			string basePath = (new FileInfo(topLevelFilename)).Directory.FullName;
			var sr = new StreamReader (topLevelFilename);
			var ser = new XmlSerializer (typeof (DiscoveryClientResultsFile));
			var resfile = (DiscoveryClientResultsFile) ser.Deserialize (sr);
			sr.Close ();
			
			foreach (DiscoveryClientResult dcr in resfile.Results)
			{
				// Done this cause Type.GetType(dcr.ReferenceTypeName) returned null
				Type type;
				switch (dcr.ReferenceTypeName)
				{
					case "System.Web.Services.Discovery.ContractReference":
						type = typeof(ContractReference);
						break;
					case "System.Web.Services.Discovery.DiscoveryDocumentReference":
						type = typeof(DiscoveryDocumentReference);
						break;
					default:
						continue;
				}
				
				var dr = (DiscoveryReference) Activator.CreateInstance(type);
				dr.Url = dcr.Url;
				var fs = new FileStream (Path.Combine(basePath, dcr.Filename), FileMode.Open, FileAccess.Read);
				Documents.Add (dr.Url, dr.ReadDocument (fs));
				fs.Close ();
				References.Add (dr.Url, dr);
			}
			return resfile.Results;	
		}
开发者ID:Kalnor,项目名称:monodevelop,代码行数:43,代码来源:DiscoveryProtocol.cs


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