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

C# Serialization.XmlRootAttribute类代码示例

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

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



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

示例1: Import

        public ImportResult Import(Stream inputStream)
        {
            _log.Debug("Import started");

            var root = new XmlRootAttribute("Results");
            var serializer = new XmlSerializer(typeof(ExportObject[]), root);

            var deserialized = (ExportObject[])serializer.Deserialize(inputStream);

            _log.Debug("Imported {0} objects", deserialized.Length);

            if (deserialized.Length == 0)
            {
                return new ImportResult(Enumerable.Empty<RmResource>(), Enumerable.Empty<RmResource>());
            }

            string primaryObjectsType = deserialized[0].ResourceManagementObject.ObjectType;

            _log.Debug("Detected {0} as primary import type", primaryObjectsType);

            var allImportedObjects = deserialized.Select(x => ConvertToResource(x))
                .ToList();
            var primaryObjects = allImportedObjects.Where(x => x.ObjectType == primaryObjectsType)
                .ToList();

            _log.Debug("Imported {0} primary objects", primaryObjects.Count);

            return new ImportResult(primaryObjects, allImportedObjects);
        }
开发者ID:Predica,项目名称:FimClient,代码行数:29,代码来源:XmlImporter.cs


示例2: WriteObject

		public bool WriteObject(XPathResult result, XPathNavigator node, object value)
		{
			var rootOverride = new XmlRootAttribute(node.LocalName)
			{
				Namespace = node.NamespaceURI
			};

			var xml = new StringBuilder();
			var settings = new XmlWriterSettings
			{
				OmitXmlDeclaration = true,
				Indent = false
			};
			var namespaces = new XmlSerializerNamespaces();
			namespaces.Add(string.Empty, string.Empty);
			if (string.IsNullOrEmpty(node.NamespaceURI) == false)
			{
				var prefix = result.Context.AddNamespace(node.NamespaceURI);
				namespaces.Add(prefix, node.NamespaceURI);
			}

			var serializer = new XmlSerializer(result.Type, rootOverride);

			using (var writer = XmlWriter.Create(xml, settings))
			{
				serializer.Serialize(writer, value, namespaces);
				writer.Flush();
			}

			node.ReplaceSelf(xml.ToString());

			return true;
		}
开发者ID:ThatExtraBit,项目名称:Castle.Core,代码行数:33,代码来源:DefaultXmlSerializer.cs


示例3: BothCounters

		public void BothCounters()
		{
			using (XmlSerializerCache cache = new XmlSerializerCache())
			{
				string instanceName = PerfCounterManagerTests.GetCounterInstanceName(0);
				using (PerformanceCounter instanceCounter = new PerformanceCounter(PerfCounterManagerTests.CATEGORY
					, PerfCounterManagerTests.CACHED_INSTANCES_NAME
					, instanceName
					, true))
				{
					Assert.AreEqual(0, instanceCounter.RawValue);
					using (PerformanceCounter hitCounter = new PerformanceCounter(PerfCounterManagerTests.CATEGORY
						, PerfCounterManagerTests.SERIALIZER_HITS_NAME
						, instanceName
						, true))
					{
						Assert.AreEqual(0, hitCounter.RawValue);
						XmlRootAttribute root = new XmlRootAttribute( "theRoot" );
						XmlSerializer ser = cache.GetSerializer(typeof(SerializeMe), root);

						Assert.AreEqual(1, instanceCounter.RawValue);
						Assert.AreEqual(0, hitCounter.RawValue);
						ser = cache.GetSerializer(typeof(SerializeMe), root);

						Assert.AreEqual(1, instanceCounter.RawValue);
						Assert.AreEqual(1, hitCounter.RawValue);

					}
				}
			}
		}
开发者ID:zanyants,项目名称:mvp.xml,代码行数:31,代码来源:PerfCounterTests.cs


示例4: ProxyType

        public ProxyType(Type type)
        {
            var envTypes = new List<Type>();
            var methods =
                (from method in type.GetMethods(BindingFlags.Instance | BindingFlags.Public)
               .Where(method => Attribute.IsDefined(method, typeof(ServiceMethodAttribute)))
                 select new
                 {
                     MethodName = method.Name,
                     ServiceAttribute = (ServiceMethodAttribute)Attribute.GetCustomAttribute(method, typeof(ServiceMethodAttribute))
                 }).ToArray();

            var mappings = (from m in methods select new
                {
                  MethodName = m.MethodName,
                  Action = m.ServiceAttribute.Action,
                  ArgsTypeIndex = AddOrGetIndexOfExistingType(envTypes, m.ServiceAttribute.ArgType),
                  ResultsTypeIndex = AddOrGetIndexOfExistingType(envTypes, m.ServiceAttribute.ReturnType)
                }).ToArray();

            var xmlRoot = new XmlRootAttribute("Command");
            var envSerializers = envTypes.ConvertAll<XmlSerializer>(t => new XmlSerializer(t, xmlRoot));
            foreach (var m in mappings)
            {
                var svcMethod = new ServiceMethodInfo()
                {
                    MethodName = m.MethodName,
                    ServiceAction = m.Action,
                    ArgsSerializer = envSerializers[m.ArgsTypeIndex],
                    ResultsSerializer = envSerializers[m.ResultsTypeIndex]
                };
                _methods.Add(svcMethod.MethodName, svcMethod);
            }
        }
开发者ID:dmziryanov,项目名称:ApecAuto,代码行数:34,代码来源:ProxyType.cs


示例5: Map

		private XmlTypeMapping Map(Type t, XmlRootAttribute root)
		{
			XmlReflectionImporter ri = new XmlReflectionImporter();
			XmlTypeMapping tm = ri.ImportTypeMapping(t, root);

			return tm;
		}
开发者ID:jjenki11,项目名称:blaze-chem-rendering,代码行数:7,代码来源:XmlReflectionImporterTests.cs


示例6: Create

 public object Create(object parent, object configContext, XmlNode section)
 {
     var xRoot = new XmlRootAttribute { ElementName = section.Name, IsNullable = true };
     var ser = new XmlSerializer(GetType(), xRoot);
     var xNodeReader = new XmlNodeReader(section);
     return ser.Deserialize(xNodeReader);
 }
开发者ID:bitpantry,项目名称:BitPantry.Parsing.Strings,代码行数:7,代码来源:ConfigurationHandler.cs


示例7: XmlSerializer

 /// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer"]/*' />
 /// <devdoc>
 ///    <para>[To be supplied.]</para>
 /// </devdoc>
 public XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace) {
     XmlReflectionImporter importer = new XmlReflectionImporter(overrides, defaultNamespace);
     for (int i = 0; i < extraTypes.Length; i++)
         importer.IncludeType(extraTypes[i]);
     tempAssembly = GenerateTempAssembly(importer.ImportTypeMapping(type, root));
     this.events.sender = this;
 }
开发者ID:ArildF,项目名称:masters,代码行数:11,代码来源:xmlserializer.cs


示例8: Serialize

        /// <summary>
        /// Serializes an object into an XML document
        /// </summary>
        /// <param name="obj">object to serialize</param>
        /// <param name="rootAttribute">root attribute to use</param>
        /// <param name="namespacePrefixes">namespace prefixes</param>
        /// <returns>a string that contains the XML document</returns>
        public static string Serialize(object obj, XmlRootAttribute rootAttribute, params XmlQualifiedName[] namespacePrefixes)
        {
            if (obj == null)
            {
                return null;
            }

            using (var textWriter = new StringWriterUTF8())
            {
                var type = obj.GetType();
                var xmlAttributeOverrides = new XmlAttributeOverrides();
                if (rootAttribute != null)
                {
                    var xmlAttributes = new XmlAttributes();
                    xmlAttributes.XmlRoot = rootAttribute;
                    xmlAttributeOverrides.Add(type, xmlAttributes);
                }
                using (var xmWriter = XmlWriter.Create(textWriter, new XmlWriterSettings() { OmitXmlDeclaration = true }))
                {
                    var namespaces = new XmlSerializerNamespaces();
                    if (namespacePrefixes != null)
                    {
                        foreach (var ns in namespacePrefixes)
                        {
                            namespaces.Add(ns.Name, ns.Namespace);
                        }
                    }
                    new XmlSerializer(type, xmlAttributeOverrides).Serialize(xmWriter, obj, namespaces);
                }
                return textWriter.ToString();
            }
        }
开发者ID:kakone,项目名称:SSDP.Portable,代码行数:39,代码来源:XmlSerializerUtility.cs


示例9: getRequestContent

        public byte[] getRequestContent( string doctype, string root, Type type, object obj)
        {
            XmlSerializer serializer = null;
            if (root == null)
            {
                //... root element will be the object type name
                serializer = new XmlSerializer(type);
            }
            else
            {
                //... root element set explicitely
                var xattribs = new XmlAttributes();
                var xroot = new XmlRootAttribute(root);
                xattribs.XmlRoot = xroot;
                var xoverrides = new XmlAttributeOverrides();
                xoverrides.Add(type, xattribs);
                serializer = new XmlSerializer(type, xoverrides);
            }
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = false;
            settings.OmitXmlDeclaration = false;
            settings.Encoding = new UTF8Encoding(false/*no BOM*/, true/*throw if input illegal*/);

            XmlSerializerNamespaces xmlNameSpace = new XmlSerializerNamespaces();
            xmlNameSpace.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
            xmlNameSpace.Add("noNamespaceSchemaLocation", m_schemadir + "/" + doctype + "." + m_schemaext);

            StringWriter sw = new StringWriter();
            XmlWriter xw = XmlWriter.Create( sw, settings);
            xw.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");

            serializer.Serialize(xw, obj, xmlNameSpace);

            return settings.Encoding.GetBytes( sw.ToString());
        }
开发者ID:ProjectTegano,项目名称:Tegano,代码行数:35,代码来源:Serializer.cs


示例10: Serialize

        //users [LOGIN]
        public static void Serialize(List<User> iList, string iFileName)
        {
            UsersCollection Coll = new UsersCollection();
            foreach (User usr in iList)
            {
                Coll.uList.Add(usr);
            }

            XmlRootAttribute RootAttr = new XmlRootAttribute();
            RootAttr.ElementName = "UsersCollection";
            RootAttr.IsNullable = true;
            XmlSerializer Serializer = new XmlSerializer(typeof(UsersCollection), RootAttr);
            StreamWriter StreamWriter = null;
            try
            {
                StreamWriter = new StreamWriter(iFileName);
                Serializer.Serialize(StreamWriter, Coll);
            }
            catch (Exception Ex)
            {
                Console.WriteLine("Exception while writing into DB: " + Ex.Message);
            }
            finally
            {
                if (null != StreamWriter)
                {
                    StreamWriter.Dispose();
                }
            }
        }
开发者ID:Wilczek770,项目名称:Przychodnia_final,代码行数:31,代码来源:DBManager.cs


示例11: Initialize

        private void Initialize(Type type, string rootName, string rootNamespace, XmlSerializer xmlSerializer)
        {
            if (type == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("type");
            }
            _rootType = type;
            _rootName = rootName;
            _rootNamespace = rootNamespace == null ? string.Empty : rootNamespace;
            _serializer = xmlSerializer;

            if (_serializer == null)
            {
                if (_rootName == null)
                    _serializer = new XmlSerializer(type);
                else
                {
                    XmlRootAttribute xmlRoot = new XmlRootAttribute();
                    xmlRoot.ElementName = _rootName;
                    xmlRoot.Namespace = _rootNamespace;
                    _serializer = new XmlSerializer(type, xmlRoot);
                }
            }
            else
                _isSerializerSetExplicit = true;

            //try to get rootName and rootNamespace from type since root name not set explicitly
            if (_rootName == null)
            {
                XmlTypeMapping mapping = new XmlReflectionImporter(null).ImportTypeMapping(_rootType);
                _rootName = mapping.ElementName;
                _rootNamespace = mapping.Namespace;
            }
        }
开发者ID:SoumikMukherjeeDOTNET,项目名称:wcf,代码行数:34,代码来源:XmlSerializerObjectSerializer.cs


示例12: Application_Start

        protected void Application_Start()
        {
            log4net.Config.XmlConfigurator.Configure();

            GlobalConfiguration.Configure(WebApiConfig.Register);

            GlobalConfiguration.Configuration.Formatters.JsonFormatter.AddUriPathExtensionMapping("json", "application/json");
            GlobalConfiguration.Configuration.Formatters.XmlFormatter.AddUriPathExtensionMapping("xml", "text/xml");

            // Add a text/plain formatter (WebApiContrib also contains CSV and other formaters)
            GlobalConfiguration.Configuration.Formatters.Add(new PlainTextFormatter());

            XmlMediaTypeFormatter formatter = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
            formatter.UseXmlSerializer = true;

            // Set up serializer configuration for data object:
            XmlRootAttribute studentPersonalsXmlRootAttribute = new XmlRootAttribute("LearnerPersonals") { Namespace = SettingsManager.ProviderSettings.DataModelNamespace, IsNullable = false };
            ISerialiser<List<LearnerPersonal>> studentPersonalsSerialiser = SerialiserFactory.GetXmlSerialiser<List<LearnerPersonal>>(studentPersonalsXmlRootAttribute);
            formatter.SetSerializer<List<LearnerPersonal>>((XmlSerializer)studentPersonalsSerialiser);

            // Configure global exception loggers for unexpected errors.
            GlobalConfiguration.Configuration.Services.Add(typeof(IExceptionLogger), new TraceExceptionLogger());

            // Configure a global exception handler for unexpected errors.
            GlobalConfiguration.Configuration.Services.Replace(typeof(IExceptionHandler), new GlobalUnexpectedExceptionHandler());

            Trace.TraceInformation("********** Application_Start **********");
            log.Info("********** Application_Start **********");
            Register();
        }
开发者ID:ZiNETHQ,项目名称:sif3-framework-dotnet,代码行数:30,代码来源:Global.asax.cs


示例13: XmlMetadata

		public XmlMetadata(Type type, XmlTypeAttribute xmlType, XmlRootAttribute xmlRoot, IEnumerable<Type> xmlIncludes)
		{
			Type = type;
			XmlType = xmlType;
			XmlRoot = xmlRoot;
			XmlIncludes = xmlIncludes;
		}
开发者ID:paolocostantini,项目名称:Castle.Core,代码行数:7,代码来源:XPathBehavior.cs


示例14: getRequestContent

        public static byte[] getRequestContent(string doctype, string root, Type type, object obj)
        {
            var xattribs = new XmlAttributes();
            var xroot = new XmlRootAttribute(root);
            xattribs.XmlRoot = xroot;
            var xoverrides = new XmlAttributeOverrides();
            //... have to use XmlAttributeOverrides because .NET insists on the object name as root element name otherwise ([XmlRoot(..)] has no effect)
            xoverrides.Add(type, xattribs);

            XmlSerializer serializer = new XmlSerializer(type, xoverrides);
            StringWriter sw = new StringWriter();
            XmlWriterSettings wsettings = new XmlWriterSettings();
            wsettings.OmitXmlDeclaration = false;
            wsettings.Encoding = new UTF8Encoding();
            XmlWriter xw = XmlWriter.Create(sw, wsettings);
            xw.WriteProcessingInstruction("xml", "version='1.0' standalone='no'");
            //... have to write header by hand (OmitXmlDeclaration=false has no effect)
            xw.WriteDocType(root, null, doctype + ".sfrm", null);

            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("", "");
            //... trick to avoid printing of xmlns:xsi xmlns:xsd attributes of the root element

            serializer.Serialize(xw, obj, ns);
            return sw.ToArray();
        }
开发者ID:ProjectTegano,项目名称:Tegano,代码行数:26,代码来源:Serializer.cs


示例15: environmentTypes_Serialisation

        public void environmentTypes_Serialisation()
        {
            environmentType environmentType1;

            using (FileStream xmlStream = File.OpenRead(environmentXmlFile))
            {
                environmentType1 = SerialiserFactory.GetXmlSerialiser<environmentType>().Deserialise(xmlStream);
            }

            Assert.AreEqual(environmentType1.sessionToken, "2e5dd3ca282fc8ddb3d08dcacc407e8a", true, "Session token does not match.");

            environmentType environmentType2;

            using (FileStream xmlStream = File.OpenRead(environmentXmlFile))
            {
                environmentType2 = SerialiserFactory.GetXmlSerialiser<environmentType>().Deserialise(xmlStream);
            }

            Assert.AreEqual(environmentType2.sessionToken, "2e5dd3ca282fc8ddb3d08dcacc407e8a", true, "Session token does not match.");

            ICollection<environmentType> environmentTypes = new Collection<environmentType>
            {
                environmentType1,
                environmentType2
            };

            XmlRootAttribute xmlRootAttribute = new XmlRootAttribute("environments") { Namespace = SettingsManager.ConsumerSettings.DataModelNamespace, IsNullable = false };

            string xmlString = SerialiserFactory.GetXmlSerialiser<Collection<environmentType>>(xmlRootAttribute).Serialise((Collection<environmentType>)environmentTypes);
            System.Console.WriteLine(xmlString);

            environmentTypes = SerialiserFactory.GetXmlSerialiser<Collection<environmentType>>(xmlRootAttribute).Deserialise(xmlString);
            System.Console.WriteLine("Number deserialised is " + environmentTypes.Count);
        }
开发者ID:ZiNETHQ,项目名称:sif3-framework-dotnet,代码行数:34,代码来源:SerialisationUtilsTest.cs


示例16: Main

        static void Main(string[] args)
        {
            currentservicedata CurrentServiceData_ = new currentservicedata();

            FileStream fs = new FileStream("output.xml", FileMode.Create, FileAccess.Write);

            XmlRootAttribute xRoot = new XmlRootAttribute();
            xRoot.ElementName = "currentservicedata";
            xRoot.IsNullable = true;

            channel channel = new channel();

            channel.Name = "Stereo";
            channel.pid = "0x01";
            channel.selected = 1;

            CurrentServiceData_.audio_channels.Add(channel);

            CurrentServiceData_.current_event.date = DateTime.Now.ToShortDateString();
            CurrentServiceData_.current_event.description = "Sendungsname";
            CurrentServiceData_.current_event.details = "Beschreibungstext blah blah";
            CurrentServiceData_.current_event.duration = "90";
            CurrentServiceData_.current_event.start = DateTime.Now.ToShortDateString();
            CurrentServiceData_.current_event.time = DateTime.Now.ToShortTimeString();

            CurrentServiceData_.next_event = CurrentServiceData_.current_event;
            CurrentServiceData_.service.name = "Sendername";
            CurrentServiceData_.service.reference = "reference";

            System.Xml.Serialization.XmlSerializer xmls = new XmlSerializer(CurrentServiceData_.GetType(),xRoot);
            xmls.Serialize(fs, CurrentServiceData_);

            fs.Close();
        }
开发者ID:bietiekay,项目名称:YAPS,代码行数:34,代码来源:Program.cs


示例17: XmlSerializerWrap

 /// <summary>
 ///     Initializes a new instance of the <see cref="T:System.Xml.Serialization.XmlSerializer"/> class that can serialize objects of type <see cref="T:System.Object"/> into XML document instances, and deserialize XML document instances into objects of type <see cref="T:System.Object"/>. Each object to be serialized can itself contain instances of classes, which this overload overrides with other classes. This overload also specifies the default namespace for all the XML elements and the class to use as the XML root element.
 /// </summary>
 /// <param name="type">The type of the object that this <see cref="T:System.Xml.Serialization.XmlSerializer"/> can serialize. </param><param name="overrides">An <see cref="T:System.Xml.Serialization.XmlAttributeOverrides"/> that extends or overrides the behavior of the class specified in the <paramref name="type"/> parameter. </param><param name="extraTypes">A <see cref="T:System.Type"/> array of additional object types to serialize. </param><param name="root">An <see cref="T:System.Xml.Serialization.XmlRootAttribute"/> that defines the XML root element properties. </param><param name="defaultNamespace">The default namespace of all XML elements in the XML document. </param>
 public XmlSerializerWrap(Type type,
                          XmlAttributeOverrides overrides,
                          Type[] extraTypes,
                          XmlRootAttribute root,
                          string defaultNamespace)
 {
     this.XmlSerializerInstance = new XmlSerializer(type, overrides, extraTypes, root, defaultNamespace);
 }
开发者ID:YannBrulhart,项目名称:SystemWrapper-1,代码行数:12,代码来源:XmlSerializerWrap.cs


示例18: ElementNameDefault

		public void ElementNameDefault ()
		{
			XmlRootAttribute attr = new XmlRootAttribute ();
			Assert.AreEqual (string.Empty, attr.ElementName, "#1");

			attr.ElementName = null;
			Assert.AreEqual (string.Empty, attr.ElementName, "#2");
		}
开发者ID:nobled,项目名称:mono,代码行数:8,代码来源:XmlRootAttributeTests.cs


示例19: DataTypeDefault

		public void DataTypeDefault ()
		{
			XmlRootAttribute attr = new XmlRootAttribute ();
			Assert.AreEqual (string.Empty, attr.DataType, "#1");

			attr.DataType = null;
			Assert.AreEqual (string.Empty, attr.DataType, "#2");
		}
开发者ID:nobled,项目名称:mono,代码行数:8,代码来源:XmlRootAttributeTests.cs


示例20: GenerateKey

 internal static string GenerateKey(Type type, XmlRootAttribute root, string ns)
 {
     if (root == null)
     {
         root = (XmlRootAttribute) XmlAttributes.GetAttr(type, typeof(XmlRootAttribute));
     }
     return (type.FullName + ":" + ((root == null) ? string.Empty : root.Key) + ":" + ((ns == null) ? string.Empty : ns));
 }
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:8,代码来源:XmlMapping.cs



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
C# Serialization.XmlSchemaImporter类代码示例发布时间:2022-05-26
下一篇:
C# Serialization.XmlReflectionMember类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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