• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# XmlSerializer类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: DeserializeObject

 public Object DeserializeObject(String pXmlizedString)
 {
     XmlSerializer xs = new XmlSerializer(typeof(EntryList));
     MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString));
     XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
     return xs.Deserialize(memoryStream);
 }
开发者ID:jayrockk,项目名称:ATV2LO-devel,代码行数:7,代码来源:HelpFunctionsPlayground.cs


示例2: WMIBMySQL

 public WMIBMySQL()
 {
     string file = Variables.ConfigurationDirectory + Path.DirectorySeparatorChar + "unwrittensql.xml";
     Core.RecoverFile(file);
     if (File.Exists(file))
     {
         Syslog.WarningLog("There is a mysql dump file from previous run containing mysql rows that were never successfuly inserted, trying to recover them");
         XmlDocument document = new XmlDocument();
         using (TextReader sr = new StreamReader(file))
         {
             document.Load(sr);
             using (XmlNodeReader reader = new XmlNodeReader(document.DocumentElement))
             {
                 XmlSerializer xs = new XmlSerializer(typeof(Unwritten));
                 Unwritten un = (Unwritten)xs.Deserialize(reader);
                 lock (unwritten.PendingRows)
                 {
                     unwritten.PendingRows.AddRange(un.PendingRows);
                 }
             }
         }
     }
     Thread reco = new Thread(Exec) {Name = "MySQL/Recovery"};
     Core.ThreadManager.RegisterThread(reco);
     reco.Start();
 }
开发者ID:benapetr,项目名称:wikimedia-bot,代码行数:26,代码来源:MySQL.cs


示例3: Save

        public override void Save(TelemetryLap lap)
        {
            try
            {
                if (lap == null)
                    return;

                var filename = GetFileName(lap);
                if (File.Exists(filename))
                    File.Delete(filename);

                var xmlSer = new XmlSerializer(typeof (TelemetryLap));
                using (var memStm = new MemoryStream())
                {

                    xmlSer.Serialize(memStm, lap);

                    using (var stmR = new StreamReader(memStm))
                    {
                        memStm.Position = 0;
                        File.AppendAllText(filename, stmR.ReadToEnd(), Encoding.UTF8);
                    }
                }
            } catch (Exception ex)
            {
                logger.Error("Could not save xml telemetry lap", ex);
                throw ex;
            }
        }
开发者ID:Malyngo,项目名称:DirtRallyWebTelemetry,代码行数:29,代码来源:XmlTelemetryLapRepository.cs


示例4: Read

	private void Read(string filename)
	{
		XmlSerializer ser=new XmlSerializer(typeof(DataSet));
		FileStream fs=new FileStream(filename, FileMode.Open);
		DataSet ds;

		ds=(DataSet)ser.Deserialize(fs);
		fs.Close();
		
		Console.WriteLine("DataSet name: "+ds.DataSetName);
		Console.WriteLine("DataSet locale: "+ds.Locale.Name);

		foreach(DataTable t in ds.Tables) 
		{
			Console.WriteLine("Table name: "+t.TableName);
			Console.WriteLine("Table locale: "+t.Locale.Name);

			foreach(DataColumn c in t.Columns) 
			{
				Console.WriteLine("Column name: "+c.ColumnName);
				Console.WriteLine("Null allowed? "+c.AllowDBNull);
				
			}

			foreach(DataRow r in t.Rows)
			{
				Console.WriteLine("Row: "+(string)r[0]);
			}
		}
	}
开发者ID:nobled,项目名称:mono,代码行数:30,代码来源:dataset.cs


示例5: Run

        public override int Run(string[] args)
        {
            string schemaFileName = args[0];
            string outschemaFileName = args[1];

            XmlTextReader xr = new XmlTextReader(schemaFileName);
            SchemaInfo schemaInfo = SchemaManager.ReadAndValidateSchema(xr, Path.GetDirectoryName(schemaFileName));
            schemaInfo.Includes.Clear();
            schemaInfo.Classes.Sort(CompareNames);
            schemaInfo.Relations.Sort(CompareNames);

            XmlSerializer ser = new XmlSerializer(typeof(SchemaInfo));
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", SchemaInfo.XmlNamespace);

            using (FileStream fs = File.Create(outschemaFileName))
            {
                try
                {
                    ser.Serialize(fs, schemaInfo, ns);
                }
                finally
                {
                    fs.Flush();
                    fs.Close();
                }
            }

            return 0;
        }
开发者ID:valery-shinkevich,项目名称:sooda,代码行数:30,代码来源:CommandGenFullSchema.cs


示例6: GetDefault

        public config GetDefault()
        {
            config config;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.buy4.com/api/toolbar/config.xml");

            request.KeepAlive = false;
            request.Method = "GET";
            request.ContentType = "text/xml";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            XmlSerializer serializer = new XmlSerializer(typeof(config));
            Stream stream = response.GetResponseStream();

            using (XmlReader reader = XmlReader.Create(stream))
                {
                config = (config)serializer.Deserialize(reader);

                }

            stream.Close();

            return config;
        }
开发者ID:grefly,项目名称:Buy4,代码行数:25,代码来源:ConfigurationService.cs


示例7: ExportProteinSettings

    public void ExportProteinSettings()
    {
        try
        {
            CutParametersContainer exportParams = new CutParametersContainer();

            foreach (CutObject cuto in SceneManager.Get.CutObjects)
            {
                CutObjectProperties props = new CutObjectProperties();
                props.ProteinTypeParameters = cuto.IngredientCutParameters;
                props.Inverse = cuto.Inverse;
                props.CutType = (int)cuto.CutType;
                props.rotation = cuto.transform.rotation;
                props.position = cuto.transform.position;
                props.scale = cuto.transform.localScale;
                exportParams.CutObjectProps.Add(props);            
            }

            ////write
            serializer = new XmlSerializer(typeof(CutParametersContainer));
            stream = new FileStream(path, FileMode.Create);
            serializer.Serialize(stream, exportParams);
            stream.Close();
        }
        catch(Exception e)
        {
            Debug.Log("export failed: " + e.ToString());
            return;
        }

        Debug.Log("exported cutobject settings to " + path);
    }
开发者ID:jaronimoe,项目名称:cellVIEW_animated,代码行数:32,代码来源:tmp_util.cs


示例8: GetStdAsync

 public async Task<SummaryTemperatureData> GetStdAsync()
 {
     // var uri = new Uri("http://jeffa.org:81/ha/SummaryData.php");
     //var uri = new Uri(App.SummaryDataUrl);
     //var client = new HttpClient();
     //var opContent = (await client.GetAsync(uri)).Content;
     //string foo = await opContent.ReadAsStringAsync();
     //var fooo = JsonConvert.DeserializeObjectAsync<SummaryTemperatureData>(foo);
     //return await fooo;
     var applicationDataSettingsService = new ApplicationDataSettingsService();
     try
     {
     // ToDo need to wrap this a bit. error checking. disposal....
     WebHeaderCollection headers = new WebHeaderCollection();
     WebRequest request = WebRequest.Create(new Uri(applicationDataSettingsService.SummaryDataUrl));
     request.ContentType = "application/xml";
     WebResponse response = await request.GetResponseAsync();
     // response.Close(); // ?? hmmm
     Debug.WriteLine("\nThe HttpHeaders are \n{0}", request.Headers);
     Stream inputStream = response.GetResponseStream();
     XmlReader xmlReader = XmlReader.Create(inputStream);
     XmlSerializer xml = new XmlSerializer(typeof(SummaryTemperatureData));
     var stdXml = (SummaryTemperatureData)xml.Deserialize(xmlReader);
     return stdXml;
     }
     catch (Exception e)
     {
         Utility.Log(this, e.ToString());
         return null;
     }
 }
开发者ID:jhalbrecht,项目名称:HomeAmation,代码行数:31,代码来源:HomeAmationDataService.cs


示例9: StripResponseElement

        public PipelineContinuation StripResponseElement(ICommunicationContext context)
        {
            var passedApiUrl
                = (string)context.PipelineData["ApiUrl"];

            if (string.IsNullOrEmpty(passedApiUrl))
                return PipelineContinuation.Continue;

            var xmlDocument
                = (XmlDocument)context.PipelineData["ApiXmlResponse"];

            // read and remove response header to get result
            var responseElement = xmlDocument.SelectSingleNode("/response");
            var responseStatusAttribute = responseElement.Attributes["status"];

            var innerXml = responseElement.InnerXml;
            var stringReader = new StringReader(innerXml);

            // get the type
            Type generatedType = responseStatusAttribute.InnerText == "ok"
                                 	? _typeGenerator.GenerateType(passedApiUrl)
                                 	: typeof(Error);

            var serializer = new XmlSerializer(generatedType);
            object deserialized = serializer.Deserialize(stringReader);

            if (responseStatusAttribute.InnerText == "ok")
                context.OperationResult = new OperationResult.OK(deserialized);
            else
                context.OperationResult = new OperationResult.BadRequest { ResponseResource = deserialized };

            return PipelineContinuation.Continue;
        }
开发者ID:gregsochanik,项目名称:sevendigital-api-proxy,代码行数:33,代码来源:StripLegacyResponse.cs


示例10: LoadUpdateFileFromStream

 public static UpdateFileInfo LoadUpdateFileFromStream(Stream xmlStream)
 {
     XmlSerializer serializer = new XmlSerializer(typeof(UpdateFileInfo));
     XmlTextReader xmlTextReader = new XmlTextReader(xmlStream);
     _updateFile = (UpdateFileInfo)serializer.Deserialize(xmlTextReader);
     return _updateFile;
 }
开发者ID:jesszgc,项目名称:VideoConvert,代码行数:7,代码来源:Updater.cs


示例11: LoadUpdateFile

 public static UpdateFileInfo LoadUpdateFile(string fileName)
 {
     XmlSerializer serializer = new XmlSerializer(typeof(UpdateFileInfo));
     XmlTextReader xmlTextReader = new XmlTextReader(fileName);
     _updateFile = (UpdateFileInfo)serializer.Deserialize(xmlTextReader);
     return _updateFile;
 }
开发者ID:jesszgc,项目名称:VideoConvert,代码行数:7,代码来源:Updater.cs


示例12: Read

        /// <summary>
        /// Reads the PAP message from the specified stream.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <returns></returns>
        public static PapMessage Read(Stream stream)
        {
            XmlReaderSettings settings =
                new XmlReaderSettings
                {
                    CheckCharacters = true,
                    CloseInput = true,
                    ConformanceLevel = System.Xml.ConformanceLevel.Document,
                    DtdProcessing = DtdProcessing.Parse,
                    IgnoreComments = true,
                    ValidationType = ValidationType.DTD
                };
            XmlReader reader = XmlReader.Create(stream, settings);
            try
            {
                // Deserialize the data
                XmlSerializer serializer = new XmlSerializer(typeof(PapRoot));
                object resultRoot = serializer.Deserialize(reader);

                // Extract the response object from the appropriate root
                PapMessage response = null;
                if (resultRoot is PapRoot)
                {
                    response = ((PapRoot)resultRoot).Response;
                }

                return response;
            }
            finally
            {
                reader.Close();
            }
        }
开发者ID:ngoossens,项目名称:PushSharp,代码行数:38,代码来源:PapMessageParser.cs


示例13: Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            String xmlText = "";

            Account acc = new Account();
            acc.Address = "dsdsds";
            acc.Country = "india";
            acc.Id = "12312";
            acc.Name = "pravin";
            acc.Phone = "2323232";
            acc.Sex = "male";

            XmlSerializer ser = new XmlSerializer(acc.GetType());

            StringWriter stringWriter = new StringWriter();

            using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter))
            {
                ser.Serialize(xmlWriter, acc);

            }

            xmlText = stringWriter.ToString();

            UCTest1.SetText(xmlText);
        }
开发者ID:Giggs,项目名称:Assigenment,代码行数:26,代码来源:Defauslt2.aspx.cs


示例14: ProcessRequest

        protected override byte[] ProcessRequest(string path, Stream request,
                IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            AssetBase asset;
            XmlSerializer xs = new XmlSerializer(typeof(AssetBase));

            try
            {
                asset = (AssetBase)xs.Deserialize(request);
            }
            catch (Exception)
            {
                httpResponse.StatusCode = (int)HttpStatusCode.BadRequest;
                return null;
            }

            string[] p = SplitParams(path);
            if (p.Length > 0)
            {
                string id = p[0];
                bool result = m_AssetService.UpdateContent(id, asset.Data);

                xs = new XmlSerializer(typeof(bool));
                return ServerUtils.SerializeResult(xs, result);
            }
            else
            {
                string id = m_AssetService.Store(asset);

                xs = new XmlSerializer(typeof(string));
                return ServerUtils.SerializeResult(xs, id);
            }
        }
开发者ID:RutgersUniversityVirtualWorlds,项目名称:opensim,代码行数:33,代码来源:AssetServerPostHandler.cs


示例15: ReadConfig

 private static CassandraSharpConfig ReadConfig(XmlDocument xmlDoc)
 {
     XmlSerializer xmlSer = new XmlSerializer(typeof(CassandraSharpConfig));
     //MiniXmlSerializer xmlSer = new MiniXmlSerializer(typeof(CassandraSharpConfig));
     using (XmlReader xmlReader = new XmlNodeReader(xmlDoc))
         return (CassandraSharpConfig)xmlSer.Deserialize(xmlReader);
 }
开发者ID:kpaskal,项目名称:cassandra-sharp,代码行数:7,代码来源:SectionHandler.cs


示例16: Initialize

        /// <summary>
        /// Initializes the <see cref="ConfigurationService"/>.
        /// </summary>
        /// <remarks>
		/// Retrieves <see cref="ValidationConfigurationSection"/>from the current application's default configuration. 
		/// For that <see cref="ValidationConfigurationSection"/> it does the following.
		/// <list type="bullet">
		/// <item>
		/// Configures <see cref="ErrorMessageProvider"/> base on <see cref="ValidationConfigurationSection.ErrorMessageProvider"/>.
		/// </item>
		/// <item>
		/// Goes through each <see cref="ValidationConfigurationSection.MappingDocuments"/> and calls <see cref="AddUrl(string)"/> for each <see cref="MappingDocumentElement.Url"/>.
		/// </item>
		/// </list>
		/// Calling this only performs these action on the first call. Each successive call will be ignored.
		/// If this method is called simultaneous on two different threads one thread will obtain a lock and the other thread will have to wait. 
		/// </remarks>
		/// <exception cref="ArgumentNullException">Any <see cref="MappingDocumentElement.Url"/> is null.</exception>
		/// <exception cref="ArgumentException">Any <see cref="MappingDocumentElement.Url"/>  is a <see cref="string.Empty"/>.</exception>
		/// <exception cref="FileNotFoundException">Any <see cref="MappingDocumentElement.Url"/>  cannot be found.</exception>
		/// <exception cref="WebException">The remote filename, defined by Any <see cref="MappingDocumentElement.Url"/>, cannot be resolved.-or-An error occurred while processing the request.</exception>
		/// <exception cref="DirectoryNotFoundException">Part of the filename or directory cannot be found.</exception>
		/// <exception cref="UriFormatException">Any <see cref="MappingDocumentElement.Url"/> is not a valid URI.</exception>
		public static void Initialize()
        {
        	if (!initialized)
        	{
        		lock (initializedLock)
        		{
        			if (!initialized)
        			{
        				var section = ConfigurationManager.GetSection("validationFrameworkConfiguration");
        				if (section != null)
        				{
        					var validationConfigurationSection = (ValidationConfigurationSection) section;
        					var errorMessageProviderElement = validationConfigurationSection.ErrorMessageProvider;
        					if (errorMessageProviderElement != null)
        					{
        						var type = Type.GetType(errorMessageProviderElement.TypeName, true);
        						var errorMessageProviderXmlSerializer = new XmlSerializer(type);

        						ErrorMessageProvider = (IErrorMessageProvider) errorMessageProviderXmlSerializer.Deserialize(new StringReader(errorMessageProviderElement.InnerXml));
        					}

        					if (validationConfigurationSection.MappingDocuments != null)
        					{
        						foreach (MappingDocumentElement mappingDocument in validationConfigurationSection.MappingDocuments)
        						{
        							AddUrl(mappingDocument.Url);
        						}
        					}
        				}
        				initialized = true;
        			}
        		}
        	}
        }
开发者ID:thekindofme,项目名称:.netcf-Validation-Framework,代码行数:57,代码来源:ConfigurationService.cs


示例17: setFiles

        public void setFiles(List<string> filenames)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(List<Vraag>));
            List<Vraag> liAll = new List<Vraag>();

            foreach (string filename in filenames)
            {
                FileStream fs = new FileStream(Path.Combine(@"c:\users\henk\Documents\vragen\", filename), FileMode.Open);
                List<Vraag> liVragen = (List<Vraag>)serializer.Deserialize(fs);
                fs.Close();
                liAll.AddRange(liVragen);
            }

            liAll = shuffleVragen(liAll);

            int i = 0;
            CurrentVragen = new Dictionary<int, Vraag>();
            foreach (Vraag v in liAll)
            {
                CurrentVragen.Add(i, v);
                i++;
            }
            VragenOver = new Dictionary<int, Vraag>();
            foreach (KeyValuePair<int, Vraag> entry in CurrentVragen)
            {
                VragenOver.Add( entry.Key, entry.Value );
            }
            NextIndex = 0;
        }
开发者ID:htesligte,项目名称:VragenTool,代码行数:29,代码来源:ApplicationHandler.cs


示例18: LoadUpdateList

 public static List<PackageInfo> LoadUpdateList(string fileName)
 {
     XmlSerializer serializer = new XmlSerializer(typeof(List<PackageInfo>));
     XmlTextReader xmlTextReader = new XmlTextReader(fileName);
     _updateList = (List<PackageInfo>)serializer.Deserialize(xmlTextReader);
     return _updateList;
 }
开发者ID:jesszgc,项目名称:VideoConvert,代码行数:7,代码来源:Updater.cs


示例19: Load

        public static Preferences Load()
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Preferences));
            Preferences loadedPref;

            try
            {

                using (StreamReader prefReader = new StreamReader(PrefFile))
                {
                    loadedPref = (Preferences)serializer.Deserialize(prefReader);

                }
            }
            catch (IOException)
            {
                Errors.Error("Couldn't load preferences file, using defaults");
                loadedPref = new Preferences();
            }
            catch (InvalidOperationException)
            {
                Errors.Error("Invalid preferences file, loading defaults");
                loadedPref = new Preferences();
            }

            return loadedPref;
        }
开发者ID:Bananattack,项目名称:verge3,代码行数:27,代码来源:UserPrefs.cs


示例20: MasterServer

        /// <summary>
        ///     Server constructor, starts the server and connects to all region servers.
        /// </summary>
        /// <remarks>
        ///     TODO: Make the config file be able to be in a different location. Load from command line.
        /// </remarks>
        public MasterServer()
        {
            //Load this region server's junk from xml
            XmlSerializer deserializer = new XmlSerializer(typeof(MasterConfig));
            MasterConfig masterconfig = (MasterConfig)deserializer.Deserialize(XmlReader.Create(@"C:\Users\Addie\Programming\Mobius\Mobius.Server.MasterServer\bin\Release\MasterData.xml"));
            //Start it with the name MobiusMasterServer, and let connection approvals be enabled
            var config = new NetPeerConfiguration(masterconfig.ServerName);
            config.Port = masterconfig.ServerPort;
            config.MaximumConnections = masterconfig.MaxConnections;
            config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);
            LidgrenServer = new NetServer(config);

            RegionServers = new Dictionary<ushort, NetClient>();
            foreach(RegionInfo info in masterconfig.RegionServers)
            {
                NetClient region = new NetClient(new NetPeerConfiguration(info.ServerName));
                region.Start();
                region.Connect(info.ServerIp, info.ServerPort);
                RegionServers.Add(info.RegionId, region);
            }

            //Initialize our data structures
            Users = new Dictionary<Guid, User>();
            UserIdToCharacters = new Dictionary<Guid, List<Character>>();
            //Start the server
            LidgrenServer.Start();
        }
开发者ID:addiem7c5,项目名称:Old-Stability-Stuff,代码行数:33,代码来源:MasterServer.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# XmlSeverityType类代码示例发布时间:2022-05-24
下一篇:
C# XmlSchemaForm类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap