public static PersistentVM LoadStateFromFile(string filePath) { PersistentVM persistentVM; if (File.Exists(filePath)) { XmlAttributeOverrides xmlAttributeOverride = new XmlAttributeOverrides(); XmlAttributes xmlAttribute = new XmlAttributes(); xmlAttribute.XmlIgnore = true; xmlAttributeOverride.Add(typeof(DataVirtualHardDisk), "MediaLink", xmlAttribute); xmlAttributeOverride.Add(typeof(DataVirtualHardDisk), "SourceMediaLink", xmlAttribute); xmlAttributeOverride.Add(typeof(OSVirtualHardDisk), "MediaLink", xmlAttribute); xmlAttributeOverride.Add(typeof(OSVirtualHardDisk), "SourceImageName", xmlAttribute); Type[] typeArray = new Type[1]; typeArray[0] = typeof(NetworkConfigurationSet); XmlSerializer xmlSerializer = new XmlSerializer(typeof(PersistentVM), xmlAttributeOverride, typeArray, null, null); using (FileStream fileStream = new FileStream(filePath, FileMode.Open)) { persistentVM = xmlSerializer.Deserialize(fileStream) as PersistentVM; } return persistentVM; } else { throw new ArgumentException("The file to load the role does not exist", "filePath"); } }
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; }
public static ModuleConfiguration Load(string fileName, List<Type> displayList, List<Type> deviceList, List<Type> sourceList, List<Type> mappingList) { string configurationSchemaFile = Path.ChangeExtension(fileName, "xsd"); try { XmlAttributeOverrides ovr = new XmlAttributeOverrides(); XmlAttributes attrsDevice = new XmlAttributes(); XmlAttributes attrsSource = new XmlAttributes(); XmlAttributes attrsDisplay = new XmlAttributes(); XmlAttributes attrsMapping = new XmlAttributes(); attrsMapping.XmlArrayItems.Add(new XmlArrayItemAttribute(typeof (Mapping))); foreach (Type type in sourceList) attrsSource.XmlArrayItems.Add(new XmlArrayItemAttribute(type)); foreach (Type type in deviceList) attrsDevice.XmlArrayItems.Add(new XmlArrayItemAttribute(type)); foreach (Type type in displayList) attrsDisplay.XmlArrayItems.Add(new XmlArrayItemAttribute(type)); foreach (Type type in mappingList) attrsMapping.XmlArrayItems.Add(new XmlArrayItemAttribute(type)); ovr.Add(typeof (ModuleConfiguration), "DeviceList", attrsDevice); ovr.Add(typeof (ModuleConfiguration), "SourceList", attrsSource); ovr.Add(typeof (ModuleConfiguration), "DisplayList", attrsDisplay); ovr.Add(typeof (DisplayType), "MappingList", attrsMapping); XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Schema; settings.Schemas.Add("urn:configuration-schema", configurationSchemaFile); // Проводим валидацию, отдельно от десереализации, потому-что если вместе то валится using (XmlReader reader = XmlReader.Create(fileName, settings)) while (reader.Read()) { } // Проводим десереализации без валидации, потому-что если вместе то валится XmlSerializer serializer = new XmlSerializer(typeof (ModuleConfiguration), ovr); using (XmlReader reader = XmlReader.Create(fileName)) return (ModuleConfiguration) serializer.Deserialize(reader); } catch (FileNotFoundException ex) { throw new ModuleConfigurationException(ex.FileName); } catch (XmlSchemaException ex) { throw new ModuleConfigurationException(new Uri(ex.SourceUri).AbsolutePath, ex); //configurationSchemaFile } catch (XmlException ex) { throw new ModuleConfigurationException(new Uri(ex.SourceUri).AbsolutePath, ex); } }
private void InitializeSerializer() { XmlAttributes attrs = new XmlAttributes(); XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides(); attrOverrides.Add(typeof(string), "File", attrs); attrOverrides.Add(typeof(List<string>), "Columns", attrs); attrOverrides.Add(typeof(List<List<string>>), "Rows", attrs); m_compositionXmlSerializer = new XmlSerializer(typeof(List<List<string>>), attrOverrides); m_mapSerializer = new TmxMapSerializer.Serializer.TmxMapSerializer(); }
private async void ButtonSendErrorReport_Click(object sender, RoutedEventArgs e) { var ex = Error.ToExceptionless(); ex.SetUserDescription(string.Empty, NoteTextBox.Text); ex.AddObject(HurricaneSettings.Instance.Config, "HurricaneSettings", null, null, true); if (HurricaneSettings.Instance.IsLoaded) { using (var sw = new StringWriter()) { XmlAttributeOverrides overrides = new XmlAttributeOverrides(); //DONT serialize the passwords and send them to me! XmlAttributes attribs = new XmlAttributes {XmlIgnore = true}; attribs.XmlElements.Add(new XmlElementAttribute("Passwords")); overrides.Add(typeof(ConfigSettings), "Passwords", attribs); var xmls = new XmlSerializer(typeof(ConfigSettings), overrides); xmls.Serialize(sw, HurricaneSettings.Instance.Config); var doc = new XmlDocument(); doc.LoadXml(sw.ToString()); ex.SetProperty("HurricaneSettings", JsonConvert.SerializeXmlNode(doc)); } } ex.Submit(); ((Button)sender).IsEnabled = false; StatusProgressBar.IsIndeterminate = true; await ExceptionlessClient.Default.ProcessQueueAsync(); StatusProgressBar.IsIndeterminate = false; Application.Current.Shutdown(); }
//SerialSample4\form1.cs private void button1_Click(object sender, System.EventArgs e) { //create the XmlAttributes boject XmlAttributes attrs=new XmlAttributes(); //add the types of the objects that will be serialized attrs.XmlElements.Add(new XmlElementAttribute("Book",typeof(BookProduct))); attrs.XmlElements.Add(new XmlElementAttribute("Product",typeof(Product))); XmlAttributeOverrides attrOver=new XmlAttributeOverrides(); //add to the attributes collection attrOver.Add(typeof(Inventory),"InventoryItems",attrs); //create the Product and Book objects Product newProd=new Product(); BookProduct newBook=new BookProduct(); newProd.ProductID=100; newProd.ProductName="Product Thing"; newProd.SupplierID=10; newBook.ProductID=101; newBook.ProductName="How to Use Your New Product Thing"; newBook.SupplierID=10; newBook.ISBN="123456789"; Product[] addProd={newProd,newBook}; Inventory inv=new Inventory(); inv.InventoryItems=addProd; TextWriter tr=new StreamWriter("..\\..\\..\\inventory.xml"); XmlSerializer sr=new XmlSerializer(typeof(Inventory),attrOver); sr.Serialize(tr,inv); tr.Close(); MessageBox.Show("Serialized!"); }
public static T ParseXML <T>(this string @this) where T : class { if (string.IsNullOrWhiteSpace(@this)) { return((T)Activator.CreateInstance(typeof(T))); } if ([email protected]("<?xml version=\"1.0\" encoding=\"utf-16\"?>")) { @this = "<?xml version=\"1.0\" encoding=\"utf-16\"?>" + @this; } string kUtf8BOM = System.Text.Encoding.UTF8.GetString(System.Text.Encoding.UTF8.GetPreamble()); if (@this.StartsWith(kUtf8BOM)) { @this = @this.Remove(0, kUtf8BOM.Length); } if (@this.StartsWith("?xm")) { @this = "<" + @this; } StringReader Stream = null; XmlTextReader Reader = null; try { System.Xml.Serialization.XmlAttributeOverrides xOver = new System.Xml.Serialization.XmlAttributeOverrides(); System.Xml.Serialization.XmlAttributes attrs = new System.Xml.Serialization.XmlAttributes(); foreach (var Ig in typeof(T).GetProperties().Where(c => !c.PropertyType.IsSerializable || c.PropertyType.FullName.StartsWith("DynamicBusiness.BPMS.BusinessLogic") || c.PropertyType.FullName.StartsWith("DynamicBusiness.BPMS.Engine")).Select(c => c.Name)) { attrs = new System.Xml.Serialization.XmlAttributes(); attrs.XmlIgnore = true; xOver.Add(typeof(T), Ig, attrs); } XmlSerializer Serializer = new XmlSerializer(typeof(T), xOver); Stream = new StringReader(@this); Reader = new XmlTextReader(Stream); // covert reader to object return((T)Serializer.Deserialize(Reader)); } catch (Exception ex) { return(default(T)); } finally { if (Stream != null) { Stream.Close(); } if (Reader != null) { Reader.Close(); } } }
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 static XmlAttributeOverrides Create(Type objectType) { XmlAttributeOverrides xOver = null; if (!table.TryGetValue(objectType, out xOver)) { // Create XmlAttributeOverrides object. xOver = new XmlAttributeOverrides(); /* Create an XmlTypeAttribute and change the name of the XML type. */ XmlTypeAttribute xType = new XmlTypeAttribute(); xType.TypeName = objectType.Name; // Set the XmlTypeAttribute to the XmlType property. XmlAttributes attrs = new XmlAttributes(); attrs.XmlType = xType; /* Add the XmlAttributes to the XmlAttributeOverrides, specifying the member to override. */ xOver.Add(objectType, attrs); table.MergeSafe(objectType, xOver); } return xOver; }
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(); }
/// <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 static Config GetConfig(string configFilePath) { using (var fs = new FileStream(configFilePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { XmlAttributes attributes = new XmlAttributes { XmlIgnore = true }; XmlAttributeOverrides overrides = new XmlAttributeOverrides(); overrides.Add(typeof(AlertSourceIncident), "CustomFields", attributes); // Microsoft.AzureAd.Icm.Types.TenantIdentifier cannot be serialized because it does not have a parameterless constructor. overrides.Add(typeof(AlertSourceIncident), "ServiceResponsible", attributes); overrides.Add(typeof(AlertSourceIncident), "ImpactedServices", attributes); var serializer = new XmlSerializer(typeof(Config), overrides); var configObject = (Config)serializer.Deserialize(fs); configObject.Name = Path.GetFileNameWithoutExtension(configFilePath); return configObject; } }
public void SameObjectWithRootAttribute() { XmlAttributeOverrides ov = new XmlAttributeOverrides(); XmlAttributes atts = new XmlAttributes(); atts.XmlRoot = new XmlRootAttribute("myRoot"); ov.Add(typeof(SerializeMe), atts); ThumbprintHelpers.SameThumbprint(ov, ov); }
public static void SaveStateToFile(PersistentVM role, string filePath) { if (role == null) { throw new ArgumentNullException("role", Resources.MissingPersistentVMRole); } 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); var serializer = new System.Xml.Serialization.XmlSerializer(typeof(PersistentVM), overrides, new Type[] { typeof(NetworkConfigurationSet) }, null, null); using (TextWriter writer = new StreamWriter(filePath)) { serializer.Serialize(writer, role); } }
public void WriteTo(TextWriter tw) { XmlAttributeOverrides overrides = new XmlAttributeOverrides(); XmlAttributes attrs = new XmlAttributes {XmlIgnore = true}; overrides.Add(Object.GetType(), "Id", attributes: attrs); XmlSerializer xs = new XmlSerializer(Object.GetType(), overrides); xs.Serialize(tw, Object); }
private void SerializeToXml(TransportMessage transportMessage, MemoryStream stream) { var overrides = new XmlAttributeOverrides(); var attrs = new XmlAttributes { XmlIgnore = true }; overrides.Add(typeof(TransportMessage), "Messages", attrs); overrides.Add(typeof(TransportMessage), "Address", attrs); overrides.Add(typeof(TransportMessage), "ReplyToAddress", attrs); overrides.Add(typeof(TransportMessage), "Headers", attrs); overrides.Add(typeof(TransportMessage), "Body", attrs); var xs = new XmlSerializer(typeof(TransportMessage), overrides); var doc = new XmlDocument(); using (var tempstream = new MemoryStream()) { xs.Serialize(tempstream, transportMessage); tempstream.Position = 0; doc.Load(tempstream); } var data = transportMessage.Body != null ? Encoding.UTF8.GetString(transportMessage.Body) : string.Empty; var bodyElement = doc.CreateElement("Body"); bodyElement.AppendChild(doc.CreateCDataSection(data)); doc.DocumentElement.AppendChild(bodyElement); var headers = new SerializableDictionary<string, string>(transportMessage.Headers); var headerElement = doc.CreateElement("Headers"); headerElement.InnerXml = headers.GetXml(); doc.DocumentElement.AppendChild(headerElement); var replyToAddressElement = doc.CreateElement("ReplyToAddress"); replyToAddressElement.InnerText = transportMessage.ReplyToAddress.ToString(); doc.DocumentElement.AppendChild(replyToAddressElement); doc.Save(stream); stream.Position = 0; }
public static string BuildXml <T>(this T BusinessObject) where T : class { MemoryStream Stream = null; TextWriter Writer = null; try { System.Xml.Serialization.XmlAttributeOverrides xOver = new System.Xml.Serialization.XmlAttributeOverrides(); System.Xml.Serialization.XmlAttributes attrs = new System.Xml.Serialization.XmlAttributes(); foreach (var Ig in typeof(T).GetProperties().Where(c => !c.PropertyType.IsSerializable || c.PropertyType.FullName.StartsWith("DynamicBusiness.BPMS.BusinessLogic")).Select(c => c.Name)) { attrs = new System.Xml.Serialization.XmlAttributes(); attrs.XmlIgnore = true; xOver.Add(typeof(T), Ig, attrs); } Stream = new MemoryStream(); Writer = new StreamWriter(Stream, Encoding.Unicode); XmlSerializer Serializer = new XmlSerializer(typeof(T), xOver); Serializer.Serialize(Writer, BusinessObject); int Count = (int)Stream.Length; byte[] BytesArr = new byte[Count]; Stream.Seek(0, SeekOrigin.Begin); Stream.Read(BytesArr, 0, Count); UnicodeEncoding utf = new UnicodeEncoding(); return(System.Web.HttpUtility.HtmlDecode(utf.GetString(BytesArr).Trim())); //return utf.GetString(BytesArr).Trim(); } catch (Exception exc) { DotNetNuke.Services.Exceptions.Exceptions.LogException(exc); return(string.Empty); } finally { if (Stream != null) { Stream.Close(); } if (Writer != null) { Writer.Close(); } } }
public void TwoObjectsWithSameRootAttributeDifferentTypes() { XmlAttributeOverrides ov1 = new XmlAttributeOverrides(); XmlAttributeOverrides ov2 = new XmlAttributeOverrides(); XmlAttributes atts1 = new XmlAttributes(); atts1.XmlRoot = new XmlRootAttribute("myRoot"); ov1.Add(typeof(SerializeMe), atts1); XmlAttributes atts2 = new XmlAttributes(); atts2.XmlRoot = new XmlRootAttribute("myRoot"); ov2.Add(typeof(SerializeMeToo), atts2); ThumbprintHelpers.DifferentThumbprint(ov1, ov2); }
internal XmlAttributeOverrides GetSerializerOverrides() { var overrides = new XmlAttributeOverrides(); var attributes = new XmlAttributes(); foreach (XmlElementAttribute attribute in SerializerAttributes) { attributes.XmlElements.Add(attribute); } overrides.Add(typeof(ItemData), "Typed", attributes); return overrides; }
public void SaveToFile(string path) { XmlSerializer serializer = new XmlSerializer(typeof (OptionsList)); XmlAttributeOverrides overrides = new XmlAttributeOverrides(); XmlAttributes ignoreAttr = new XmlAttributes(); ignoreAttr.XmlIgnore = true; overrides.Add(typeof (Annotatable), "IsStarred", ignoreAttr); using (StreamWriter writer = File.CreateText(path)) { serializer.Serialize(writer, this); writer.Close(); } }
static XmlSerializer GetXmlSerializer() { lock (GetXmlSerializerLock) { if (xmlSerializerForSerialization == null) { var overrides = new XmlAttributeOverrides(); var attrs = new XmlAttributes { XmlIgnore = true }; overrides.Add(typeof(TransportMessage), "Messages", attrs); xmlSerializerForSerialization = new XmlSerializer(typeof(TransportMessage), overrides); } return xmlSerializerForSerialization; } }
public static void Save(this ModuleConfiguration moduleConfiguration, string fileName, List<Type> displayList, List<Type> deviceList, List<Type> sourceList, List<Type> mappingList) { XmlAttributeOverrides ovr = new XmlAttributeOverrides(); XmlAttributes attrsDevice = new XmlAttributes(); XmlAttributes attrsSource = new XmlAttributes(); XmlAttributes attrsDisplay = new XmlAttributes(); XmlAttributes attrsMapping = new XmlAttributes(); attrsMapping.XmlArrayItems.Add(new XmlArrayItemAttribute(typeof (Mapping))); foreach (Type type in sourceList) attrsSource.XmlArrayItems.Add(new XmlArrayItemAttribute(type)); foreach (Type type in deviceList) attrsDevice.XmlArrayItems.Add(new XmlArrayItemAttribute(type)); foreach (Type type in displayList) attrsDisplay.XmlArrayItems.Add(new XmlArrayItemAttribute(type)); foreach (Type type in mappingList) attrsMapping.XmlArrayItems.Add(new XmlArrayItemAttribute(type)); ovr.Add(typeof (ModuleConfiguration), "DeviceList", attrsDevice); ovr.Add(typeof (ModuleConfiguration), "SourceList", attrsSource); ovr.Add(typeof (ModuleConfiguration), "DisplayList", attrsDisplay); ovr.Add(typeof (DisplayType), "MappingList", attrsMapping); XmlWriterSettings setting = new XmlWriterSettings(); setting.Indent = true; XmlSerializer serializer = new XmlSerializer(typeof (ModuleConfiguration), ovr, new Type[] {}, null, "urn:configuration-schema"); using (XmlWriter writer = XmlWriter.Create(fileName, setting)) { serializer.Serialize(writer, moduleConfiguration); } }
public static void SaveStateToFile(PersistentVM role, string filePath) { if (role != null) { XmlAttributeOverrides xmlAttributeOverride = new XmlAttributeOverrides(); XmlAttributes xmlAttribute = new XmlAttributes(); xmlAttribute.XmlIgnore = true; xmlAttributeOverride.Add(typeof(DataVirtualHardDisk), "MediaLink", xmlAttribute); xmlAttributeOverride.Add(typeof(DataVirtualHardDisk), "SourceMediaLink", xmlAttribute); xmlAttributeOverride.Add(typeof(OSVirtualHardDisk), "MediaLink", xmlAttribute); Type[] typeArray = new Type[1]; typeArray[0] = typeof(NetworkConfigurationSet); XmlSerializer xmlSerializer = new XmlSerializer(typeof(PersistentVM), xmlAttributeOverride, typeArray, null, null); using (TextWriter streamWriter = new StreamWriter(filePath)) { xmlSerializer.Serialize(streamWriter, role); } return; } else { throw new ArgumentNullException("role", "Role cannot be null"); } }
public XmlSerializer CreateOverrider( ) { // Create the XmlAttributeOverrides and XmlAttributes objects. XmlAttributeOverrides xOver = new XmlAttributeOverrides( ); XmlAttributes xAttrs = new XmlAttributes( ); /* Create an overriding XmlAttributeAttribute set it to the XmlAttribute property of the XmlAttributes object.*/ XmlAttributeAttribute xAttribute = new XmlAttributeAttribute( "NameTest" ); xAttrs.XmlAttribute = xAttribute; // Add to the XmlAttributeOverrides. Specify the member name. xOver.Add( typeof( Data ) , "Category" , xAttrs ); // Create the XmlSerializer and return it. return new XmlSerializer( typeof( Data ) , xOver ); }
public static XmlAttributeOverrides GetExportedScOverrides() { var _container = PluginContainer.GetOvalCompositionContainer(); var itemTypes = _container.GetExports<ItemType>().Select(exp => exp.Value.GetType()); XmlAttributeOverrides scOverrides = new XmlAttributeOverrides(); XmlAttributes itemAttributes = new XmlAttributes(); foreach (var itemType in itemTypes) { var xmlAttrs = (itemType.GetCustomAttributes(typeof(XmlRootAttribute), false) as XmlRootAttribute[]).SingleOrDefault(); itemAttributes.XmlArrayItems.Add(new XmlArrayItemAttribute(xmlAttrs.ElementName, itemType) { Namespace = xmlAttrs.Namespace }); } scOverrides.Add(typeof(oval_system_characteristics), "system_data", itemAttributes); return scOverrides; }
public void AllParams() { Type[] types1 = new Type[] { typeof(SerializeMe), typeof(SerializeMeToo) }; Type[] types2 = new Type[] { typeof(SerializeMe), typeof(SerializeMeToo) }; XmlAttributeOverrides over1 = new XmlAttributeOverrides(); XmlAttributeOverrides over2 = new XmlAttributeOverrides(); XmlAttributes atts1 = new XmlAttributes(); XmlAttributes atts2 = new XmlAttributes(); atts1.XmlType = new XmlTypeAttribute("mytype"); atts2.XmlType = new XmlTypeAttribute("mytype"); over1.Add(typeof(SerializeMe), atts1); over2.Add(typeof(SerializeMe), atts2); XmlRootAttribute root1 = new XmlRootAttribute("someelement"); XmlRootAttribute root2 = new XmlRootAttribute("someelement"); string namespace1 = "mynamespace"; string namespace2 = "mynamespace"; System.Xml.Serialization.XmlSerializer ser1 = cache.GetSerializer(typeof(SerializeMe) , over1 , types1 , root1 , namespace1); Assert.AreEqual(false, CacheHit); Assert.AreEqual(true, NewInstaceCreated); ClearFlags(); System.Xml.Serialization.XmlSerializer ser2 = cache.GetSerializer(typeof(SerializeMe) , over2 , types2 , root2 , namespace2); Assert.AreEqual(true, CacheHit); Assert.AreEqual(false, NewInstaceCreated); Assert.AreSame(ser1, ser2); }
public void XmlOverrides_can_change_root_node() { var people = new System.Collections.Generic.List<Person>() { new Person(){ Id = 5, Name = "Jeremy" }, new Person(){ Id = 1, Name = "Bob" } }; var attributes = new XmlAttributes(); attributes.XmlRoot = new XmlRootAttribute("People"); var xmlAttribueOverrides = new XmlAttributeOverrides(); xmlAttribueOverrides.Add(people.GetType(), attributes); var result = new XmlResult(people, xmlAttribueOverrides); result.ExecuteResult(_controllerContext); var doc = new XmlDocument(); doc.LoadXml(_controllerContext.HttpContext.Response.Output.ToString()); Assert.That(doc.DocumentElement.Name, Is.EqualTo("People")); }
/// <summary> /// verwerk de data in het project object tot XML file /// </summary> /// <param name="proj">te verwerken tot XML file</param> /// <param name="newFile">moet er een nieuw bestand gemaakt worden</param> /// <returns>succes boolean</returns> public bool VewerkData(Project proj, bool newFile) { if (newFile) { NewNameFile(); } filename = "result" + count.ToString() + ".xml"; // elk overridden field, property, of type heeft een XmlAttributes instance nodig. XmlAttributes xmlAttrs = new XmlAttributes(); // maken van het attribuut XmlElementAttribute attr = new XmlElementAttribute(); attr.ElementName = "newVogel"; attr.Type = typeof(Vogel); xmlAttrs.XmlElements.Add(attr); // maken van het override attribuut XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides(); // voeg de override waarde toe aan de lijst met het veld dat de inheritance heeft samen met de attribuuten attrOverrides.Add(typeof(Waarneming), "Dier", xmlAttrs); try { Type t = typeof(Code_Layer.Project); XmlSerializer xmls = new XmlSerializer(t, attrOverrides); using (FileStream fs = new FileStream(XMLPath + filename, FileMode.Create)) { xmls.Serialize(fs, proj); } } catch (Exception e)//error afhandelen { Console.WriteLine(e.Message); Console.WriteLine(e.InnerException); Console.WriteLine(e.StackTrace); return false; } return true; }
/// <summary> /// Загрузка дерева локаций из XML-файла. /// </summary> /// <param name="fileName">Имя файла.</param> /// <returns>Локация первого уровня.</returns> public static Location DeserializeLocations(string fileName) { XmlAttributes attrs = new XmlAttributes(); XmlElementAttribute attr = new XmlElementAttribute(); attr.ElementName = "Location"; attr.Type = typeof(Location); attrs.XmlElements.Add(attr); XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides(); attrOverrides.Add(typeof(Location), "Instruments", attrs); XmlSerializer writter = new XmlSerializer(typeof(Location), attrOverrides); var path = fileName; FileStream file = new FileStream(path, FileMode.Open); Location root = (Location)writter.Deserialize(file); file.Close(); return root; }
static void Main(string[] args) { Order order = new Order(3721, Guid.NewGuid()) { Date = DateTime.Today, Customer = "张三", ShipAddress = "江苏省 苏州市 星湖街 328号" }; XmlAttributes attributes = new XmlAttributes(); attributes.XmlAttribute = new XmlAttributeAttribute("ID"); XmlAttributeOverrides attributeOverrides = new XmlAttributeOverrides(); attributeOverrides.Add(typeof(Order), "ID", attributes); XmlRootAttribute rootAttribute = new XmlRootAttribute("Ord"); using (XmlWriter writer = new XmlTextWriter("order.xml", Encoding.UTF8)) { XmlSerializer serializer = new XmlSerializer(typeof(Order), attributeOverrides, null, rootAttribute, "http://www.artech.com"); serializer.Serialize(writer, order); } Process.Start("order.xml"); }
public void DeserializeObject(string filename) { XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides(); XmlAttributes attrs = new XmlAttributes(); // Create an XmlElementAttribute to override the Instrument. XmlElementAttribute attr = new XmlElementAttribute(); attr.ElementName = "Brass"; attr.Type = typeof(Brass); // Add the XmlElementAttribute to the collection of objects. attrs.XmlElements.Add(attr); attrOverrides.Add(typeof(Orchestra), "Instruments", attrs); // Create the XmlSerializer using the XmlAttributeOverrides. XmlSerializer s = new XmlSerializer(typeof(Orchestra), attrOverrides); FileStream fs = new FileStream(filename, FileMode.Open); Orchestra band = (Orchestra)s.Deserialize(fs); Console.WriteLine("Brass:"); /* The difference between deserializing the overridden XML document and serializing it is this: To read the derived object values, you must declare an object of the derived type (Brass), and cast the Instrument instance to it. */ Brass b; foreach (Instrument i in band.Instruments) { b = (Brass)i; Console.WriteLine( b.Name + "\n" + b.IsValved); } }
object IConfigurationSectionHandler.Create(object parent, object configContext, XmlNode section) { Dictionary<string, IList<AuthorizedType>> authorizedTypes = new Dictionary<string, IList<AuthorizedType>>(); XmlAttributeOverrides authorizedTypeOverrides = new XmlAttributeOverrides(); XmlAttributes authorizedTypeAttributes = new XmlAttributes(); authorizedTypeAttributes.XmlRoot = new XmlRootAttribute("authorizedType"); authorizedTypeOverrides.Add(typeof(AuthorizedType), authorizedTypeAttributes); XmlSerializer xmlSerializer = new XmlSerializer(typeof(AuthorizedType), authorizedTypeOverrides); foreach (XmlNode targetFx in section.ChildNodes) { XmlAttribute versionAttribute = targetFx.Attributes.GetNamedItem(TargetFxVersionAttribute) as XmlAttribute; if (versionAttribute != null) { string version = versionAttribute.Value; if (!string.IsNullOrEmpty(version)) { IList<AuthorizedType> versionTypes; if (!authorizedTypes.TryGetValue(version, out versionTypes)) { versionTypes = new List<AuthorizedType>(); authorizedTypes.Add(version, versionTypes); } foreach (XmlNode authorizedTypeNode in targetFx.ChildNodes) { AuthorizedType authorizedType = xmlSerializer.Deserialize(new XmlNodeReader(authorizedTypeNode)) as AuthorizedType; if (authorizedType != null) { versionTypes.Add(authorizedType); } } } } } return authorizedTypes; }