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; }
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(); }
/// <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(); } }
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); }
//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(); } } }
public static T XMLDeserialize <T>(string xml, System.Xml.Serialization.XmlRootAttribute xRoot = null) { /* * if (string.IsNullOrEmpty(xml)) * { * return default(T); * } * * XmlSerializer serializer = new XmlSerializer(typeof(T)); * * XmlReaderSettings settings = new XmlReaderSettings(); * // No settings need modifying here * * using (StringReader textReader = new StringReader(xml)) * { * using (XmlReader xmlReader = XmlReader.Create(textReader, settings)) * { * return (T)serializer.Deserialize(xmlReader); * } * }*/ XmlSerializer xs; if (xRoot != null) { xs = new XmlSerializer(typeof(T), xRoot); } else { xs = new XmlSerializer(typeof(T)); } XmlTextReader reader = new XmlTextReader(new StringReader(xml)); return((T)xs.Deserialize(reader)); }
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); }
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); } }
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(); }
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()); }
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); } } } }
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(); }
public XmlMetadata(Type type, XmlTypeAttribute xmlType, XmlRootAttribute xmlRoot, IEnumerable<Type> xmlIncludes) { Type = type; XmlType = xmlType; XmlRoot = xmlRoot; XmlIncludes = xmlIncludes; }
/// <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; }
private XmlTypeMapping Map(Type t, XmlRootAttribute root) { XmlReflectionImporter ri = new XmlReflectionImporter(); XmlTypeMapping tm = ri.ImportTypeMapping(t, root); return tm; }
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; } }
protected T ExtractCapabilities <T>(XmlElement element, string ns) { BeginStep("Parse Capabilities element in GetServices response"); System.Xml.Serialization.XmlRootAttribute xRoot = new System.Xml.Serialization.XmlRootAttribute(); xRoot.ElementName = "Capabilities"; xRoot.IsNullable = true; xRoot.Namespace = ns; System.Xml.Serialization.XmlSerializer serializer = new XmlSerializer(typeof(T), xRoot); XmlReader reader = new XmlNodeReader(element); T capabilities; try { capabilities = (T)serializer.Deserialize(reader); } catch (Exception exc) { string message; if (exc.InnerException != null) { message = string.Format("{0} {1}", exc.Message, exc.InnerException.Message); } else { message = exc.Message; } throw new ApplicationException(message); } StepPassed(); return(capabilities); }
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); }
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)); }
public static XmlSerializer Create(Type type, XmlRootAttribute root) { Type realType = GetRealType(type); XmlSerializer xs = _factory.CreateSerializer(realType, root); if (xs == null) xs = new XmlSerializer(realType, root); return xs; }
/// <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); }
public void ElementNameDefault () { XmlRootAttribute attr = new XmlRootAttribute (); Assert.AreEqual (string.Empty, attr.ElementName, "#1"); attr.ElementName = null; Assert.AreEqual (string.Empty, attr.ElementName, "#2"); }
/// <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 IXmlSerializer Create(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace) { return new XmlSerializerWrap(type, overrides, extraTypes, root, defaultNamespace); }
public void DataTypeDefault () { XmlRootAttribute attr = new XmlRootAttribute (); Assert.AreEqual (string.Empty, attr.DataType, "#1"); attr.DataType = null; Assert.AreEqual (string.Empty, attr.DataType, "#2"); }
XmlTypeMapping GetLiteralTypeMapping () { XmlRootAttribute root = new XmlRootAttribute("rootroot"); Type[] types = new Type[] {typeof(UknTestPart), typeof(AnotherTestPart), typeof(DblStringContainer) }; XmlReflectionImporter ri = new XmlReflectionImporter (); foreach (Type t in types) ri.IncludeType (t); return ri.ImportTypeMapping (typeof(Test), root); }
public static void SerializeToFile(string filePath, Object obj, XmlRootAttribute root, XmlAttributeOverrides overrides) { XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType(), overrides, null, root, string.Empty); StreamWriter streamWriter = new StreamWriter(filePath, false, new UTF8Encoding()); xmlSerializer.Serialize(streamWriter, obj); streamWriter.Close(); }
public XmlMetadata(Type type, bool? qualified, bool? isNullable, XmlTypeAttribute xmlType, XmlRootAttribute xmlRoot, IEnumerable<Type> xmlIncludes) { Type = type; Qualified = qualified; IsNullable = isNullable; XmlType = xmlType; XmlRoot = xmlRoot; XmlIncludes = xmlIncludes; }
public static List<AllClientsContact> GetAllClientsContactsFromFile( FileInfo file) { var result = new List<AllClientsContact>(); var doc = XDocument.Load( file.FullName ); var root = new XmlRootAttribute(); root.IsNullable = true; XmlSerializer serializer = new XmlSerializer(typeof(AllClientsContact),root); var clients = doc.Descendants( "AllClientsContact" ).Select( n => CommonService.FromXml( typeof( AllClientsContact ), n.ToString(),serializer ) as AllClientsContact); result.AddRange(clients.ToList()); return result; }
static AtomWriter() { XmlRootAttribute objectXmlRoot = new XmlRootAttribute("object"); objectXmlRoot.Namespace = AtomPubConstants.NamespaceRestAtom; ObjectSerializer = new XmlSerializer(typeof(cmisObjectType), objectXmlRoot); XmlRootAttribute aclXmlRoot = new XmlRootAttribute("acl"); aclXmlRoot.Namespace = AtomPubConstants.NamespaceCMIS; AclSerializer = new XmlSerializer(typeof(cmisAccessControlListType), aclXmlRoot); }
public override void ConvertObjectToXml(object value, XmlWriter xmlWriter, XmlRootAttribute xmlAttrib) { if (xmlAttrib == null) { ((IXmlSerializable) value).WriteXml(xmlWriter); } else { ObjectStorage.GetXmlSerializer(base.DataType, xmlAttrib).Serialize(xmlWriter, value); } }
private static ExchangeData ParseReturn(string response) { var settings = new XmlReaderSettings { ProhibitDtd = false, XmlResolver = null }; var strReader = new StringReader(response); var xRoot = new XmlRootAttribute {ElementName = "exchangedata", IsNullable = true}; var xmlSerializer = new XmlSerializer(typeof(ExchangeData),xRoot); var xmlReader = XmlReader.Create(strReader, settings); xmlReader.ReadToDescendant("exchangedata"); var a = (ExchangeData)xmlSerializer.Deserialize(xmlReader); return a; }
/// <summary> /// Creates an instance of <see cref="HomeUserControl"/>. /// </summary> public HomeUserControl() { InitializeComponent(); // Load Menu XmlRootAttribute xmlRootAttribute = new XmlRootAttribute("MenuDataItems"); XmlSerializer serializer = new XmlSerializer(typeof(ObservableCollection<MenuDataItem>), xmlRootAttribute); using (XmlReader reader = XmlReader.Create(FilePath.GetAbsolutePath("Menu.xml"))) { m_menuDataItems = (ObservableCollection<MenuDataItem>)serializer.Deserialize(reader); } }
/// <summary> /// serialize to xml /// </summary> /// <param name="xobj"></param> /// <param name="root"></param> /// <returns></returns> public static string ToXString(this object xobj) { string name = string.Empty; System.Attribute[] attrs = System.Attribute.GetCustomAttributes(xobj.GetType()); if (attrs.Where(a => a is System.Xml.Serialization.XmlRootAttribute).Count() > 0) { System.Xml.Serialization.XmlRootAttribute attr = (System.Xml.Serialization.XmlRootAttribute)attrs.Where(a => a is System.Xml.Serialization.XmlRootAttribute).FirstOrDefault(); name = attr.ElementName; } else { int index = xobj.GetType().FullName.LastIndexOf('.'); name = xobj.GetType().FullName.Substring(index >= 0 ? index + 1 : 0); } return(ToXmlString(xobj, name)); }
/// <summary> /// <geoloc xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://jabber.org/protocol/geoloc"><lat>32.234</lat><lon>-97.3453</lon></geoloc> /// </summary> /// <param name="obj"></param> /// <returns></returns> public static string GetXMLStringFromObject(object obj) { //MemoryStream stream = new MemoryStream(); StringWriter stream = new StringWriter(); XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces(); //namespaces. /// Get the default namespace /// Type type = obj.GetType(); object[] attr = type.GetCustomAttributes(typeof(System.Xml.Serialization.XmlRootAttribute), true); if ((attr != null) && (attr.Length > 0)) { System.Xml.Serialization.XmlRootAttribute xattr = attr[0] as System.Xml.Serialization.XmlRootAttribute; namespaces.Add("", xattr.Namespace); } XmlWriterSettings settings = new XmlWriterSettings(); settings.OmitXmlDeclaration = true; settings.Indent = true; XmlWriter writer = XmlWriter.Create(stream, settings); XmlSerializer ser = new XmlSerializer(obj.GetType()); ser.Serialize(writer, obj, namespaces); writer.Flush(); writer.Close(); string strRet = stream.ToString(); //stream.Seek(0, SeekOrigin.Begin); //byte[] bData = new byte[stream.Length]; //stream.Read(bData, 0, bData.Length); stream.Close(); stream.Dispose(); // string strRet = System.Text.UTF8Encoding.UTF8.GetString(bData, 0, bData.Length); //strRet = strRet.Replace(@"<?xml version=""1.0""?>", ""); return(strRet); }
protected T ExtractCapabilities <T>(XmlElement element, string ns) { BeginStep("Parse Capabilities element"); System.Xml.Serialization.XmlRootAttribute xRoot = new System.Xml.Serialization.XmlRootAttribute(); xRoot.ElementName = "Capabilities"; xRoot.IsNullable = true; xRoot.Namespace = ns; System.Xml.Serialization.XmlSerializer serializer = new XmlSerializer(typeof(T), xRoot); XmlReader reader = new XmlNodeReader(element); T capabilities = (T)serializer.Deserialize(reader); StepPassed(); return(capabilities); }
/// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlAttributes(MemberInfo memberInfo) { // most generic <any/> matches everithig XmlAnyElementAttribute wildcard = null; foreach (Attribute attr in memberInfo.GetCustomAttributes(false)) { if (attr is XmlIgnoreAttribute || attr is ObsoleteAttribute || attr.GetType() == IgnoreAttribute) { _xmlIgnore = true; break; } else if (attr is XmlElementAttribute) { _xmlElements.Add((XmlElementAttribute)attr); } else if (attr is XmlArrayItemAttribute) { _xmlArrayItems.Add((XmlArrayItemAttribute)attr); } else if (attr is XmlAnyElementAttribute) { XmlAnyElementAttribute any = (XmlAnyElementAttribute)attr; if ((any.Name == null || any.Name.Length == 0) && any.NamespaceSpecified && any.Namespace == null) { // ignore duplicate wildcards wildcard = any; } else { _xmlAnyElements.Add((XmlAnyElementAttribute)attr); } } else if (attr is DefaultValueAttribute) { _xmlDefaultValue = ((DefaultValueAttribute)attr).Value; } else if (attr is XmlAttributeAttribute) { _xmlAttribute = (XmlAttributeAttribute)attr; } else if (attr is XmlArrayAttribute) { _xmlArray = (XmlArrayAttribute)attr; } else if (attr is XmlTextAttribute) { _xmlText = (XmlTextAttribute)attr; } else if (attr is XmlEnumAttribute) { _xmlEnum = (XmlEnumAttribute)attr; } else if (attr is XmlRootAttribute) { _xmlRoot = (XmlRootAttribute)attr; } else if (attr is XmlTypeAttribute) { _xmlType = (XmlTypeAttribute)attr; } else if (attr is XmlAnyAttributeAttribute) { _xmlAnyAttribute = (XmlAnyAttributeAttribute)attr; } else if (attr is XmlChoiceIdentifierAttribute) { _xmlChoiceIdentifier = (XmlChoiceIdentifierAttribute)attr; } else if (attr is XmlNamespaceDeclarationsAttribute) { _xmlns = true; } } if (_xmlIgnore) { _xmlElements.Clear(); _xmlArrayItems.Clear(); _xmlAnyElements.Clear(); _xmlDefaultValue = null; _xmlAttribute = null; _xmlArray = null; _xmlText = null; _xmlEnum = null; _xmlType = null; _xmlAnyAttribute = null; _xmlChoiceIdentifier = null; _xmlns = false; } else { if (wildcard != null) { _xmlAnyElements.Add(wildcard); } } }
/// <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) : this(type, overrides, extraTypes, root, defaultNamespace, null, null) { }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer(Type type, XmlRootAttribute root) : this(type, null, Array.Empty <Type>(), root, null, null, null) { }
/// <include file='doc\XmlSerializer.uex' path='docs/doc[@for="XmlSerializer.XmlSerializer7"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> internal XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace, object location, object evidence) { if (type == null) { throw new ArgumentNullException("type"); } XmlReflectionImporter importer = new XmlReflectionImporter(overrides, defaultNamespace); if (extraTypes != null) { for (int i = 0; i < extraTypes.Length; i++) { importer.IncludeType(extraTypes[i]); } } _mapping = importer.ImportTypeMapping(type, root, defaultNamespace); _tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace); }
/// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlAttributes(ICustomAttributeProvider provider) { object[] attrs = provider.GetCustomAttributes(false); // most generic <any/> matches everything XmlAnyElementAttribute wildcard = null; for (int i = 0; i < attrs.Length; i++) { if (attrs[i] is XmlIgnoreAttribute || attrs[i] is ObsoleteAttribute || attrs[i].GetType() == IgnoreAttribute) { _xmlIgnore = true; break; } else if (attrs[i] is XmlElementAttribute) { _xmlElements.Add((XmlElementAttribute)attrs[i]); } else if (attrs[i] is XmlArrayItemAttribute) { _xmlArrayItems.Add((XmlArrayItemAttribute)attrs[i]); } else if (attrs[i] is XmlAnyElementAttribute) { XmlAnyElementAttribute any = (XmlAnyElementAttribute)attrs[i]; if ((any.Name == null || any.Name.Length == 0) && any.GetNamespaceSpecified() && any.Namespace == null) { // ignore duplicate wildcards wildcard = any; } else { _xmlAnyElements.Add((XmlAnyElementAttribute)attrs[i]); } } else if (attrs[i] is DefaultValueAttribute) { _xmlDefaultValue = ((DefaultValueAttribute)attrs[i]).Value; } else if (attrs[i] is XmlAttributeAttribute) { _xmlAttribute = (XmlAttributeAttribute)attrs[i]; } else if (attrs[i] is XmlArrayAttribute) { _xmlArray = (XmlArrayAttribute)attrs[i]; } else if (attrs[i] is XmlTextAttribute) { _xmlText = (XmlTextAttribute)attrs[i]; } else if (attrs[i] is XmlEnumAttribute) { _xmlEnum = (XmlEnumAttribute)attrs[i]; } else if (attrs[i] is XmlRootAttribute) { _xmlRoot = (XmlRootAttribute)attrs[i]; } else if (attrs[i] is XmlTypeAttribute) { _xmlType = (XmlTypeAttribute)attrs[i]; } else if (attrs[i] is XmlAnyAttributeAttribute) { _xmlAnyAttribute = (XmlAnyAttributeAttribute)attrs[i]; } else if (attrs[i] is XmlChoiceIdentifierAttribute) { _xmlChoiceIdentifier = (XmlChoiceIdentifierAttribute)attrs[i]; } else if (attrs[i] is XmlNamespaceDeclarationsAttribute) { _xmlns = true; } } if (_xmlIgnore) { _xmlElements.Clear(); _xmlArrayItems.Clear(); _xmlAnyElements.Clear(); _xmlDefaultValue = null; _xmlAttribute = null; _xmlArray = null; _xmlText = null; _xmlEnum = null; _xmlType = null; _xmlAnyAttribute = null; _xmlChoiceIdentifier = null; _xmlns = false; } else { if (wildcard != null) { _xmlAnyElements.Add(wildcard); } } }
public XmlSerializer(System.Type type, System.Xml.Serialization.XmlRootAttribute root) { }
public XmlSerializer(System.Type type, System.Xml.Serialization.XmlAttributeOverrides overrides, System.Type[] extraTypes, System.Xml.Serialization.XmlRootAttribute root, string defaultNamespace) { }