public XmlNode(string name, XmlAttributes attributes, XmlNode parent, params IXmlWriteable[] children) { Name = name; Attributes = attributes; Parent = parent; Children = children; }
public void Run() { DTO dto = new DTO { additionalInformation = "This information will be serialized separately", stamp = DateTime.UtcNow, name = "Marley", value = 72.34, index = 7 }; // this will allow us to omit the xmlns:xsi namespace var ns = new XmlSerializerNamespaces(); ns.Add( "", "" ); XmlSerializer s1 = new XmlSerializer(typeof(DTO)); var builder = new System.Text.StringBuilder(); var settings = new XmlWriterSettings { OmitXmlDeclaration = true, Indent= true }; Console.WriteLine("\nSerialize using the in-line (compile-time) attributes: "); using ( XmlWriter writer = XmlWriter.Create(builder, settings)) { s1.Serialize(writer, dto, ns); } Console.WriteLine("{0}",builder.ToString()); Console.WriteLine("\n"); // use a default namespace ns = new XmlSerializerNamespaces(); string myns = "urn:www.example.org"; ns.Add( "", myns ); XmlAttributeOverrides overrides = new XmlAttributeOverrides(); XmlAttributes attrs = new XmlAttributes(); // override the (implicit) XmlRoot attribute XmlRootAttribute attr1 = new XmlRootAttribute { Namespace = myns, ElementName = "DTO-Annotations", }; attrs.XmlRoot = attr1; overrides.Add(typeof(DTO), attrs); // "un-ignore" the first property // define an XmlElement attribute, for a type of "String", with no namespace var a2 = new XmlElementAttribute(typeof(String)) { ElementName="note", Namespace = myns }; // add that XmlElement attribute to the 2nd bunch of attributes attrs = new XmlAttributes(); attrs.XmlElements.Add(a2); attrs.XmlIgnore = false; // add that bunch of attributes to the container for the type, and // specifically apply that bunch to the "Label" property on the type. overrides.Add(typeof(DTO), "additionalInformation", attrs); // ignore the other properties // add the XmlIgnore attribute to the 2nd bunch of attributes attrs = new XmlAttributes(); attrs.XmlIgnore = true; // add that bunch of attributes to the container for the type, and // specifically apply that bunch to the "Label" property on the type. overrides.Add(typeof(DTO), "stamp", attrs); overrides.Add(typeof(DTO), "name", attrs); overrides.Add(typeof(DTO), "value", attrs); overrides.Add(typeof(DTO), "index", attrs); XmlSerializer s2 = new XmlSerializer(typeof(DTO), overrides); Console.WriteLine("\nSerialize using the override attributes: "); builder.Length = 0; using ( XmlWriter writer = XmlWriter.Create(builder, settings)) { s2.Serialize(writer, dto, ns); } Console.WriteLine("{0}",builder.ToString()); Console.WriteLine("\n"); }
public T Parse(string body, Type type) { string key = type.FullName; XmlSerializer serializer = null; bool incl = false; rwLock.AcquireReaderLock(50); try { if (rwLock.IsReaderLockHeld) { incl = parsers.TryGetValue(key, out serializer); } } finally { if (rwLock.IsReaderLockHeld) { rwLock.ReleaseReaderLock(); } } if (!incl || serializer == null) { XmlAttributes rootAttrs = new XmlAttributes(); rootAttrs.XmlRoot = new XmlRootAttribute(Constants.QM_ROOT_TAG_RSP); XmlAttributeOverrides attrOvrs = new XmlAttributeOverrides(); attrOvrs.Add(type, rootAttrs); serializer = new XmlSerializer(type, attrOvrs); rwLock.AcquireWriterLock(50); try { if (rwLock.IsWriterLockHeld) { parsers[key] = serializer; } } finally { if (rwLock.IsWriterLockHeld) { rwLock.ReleaseWriterLock(); } } } object obj = null; using (System.IO.Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(body))) { obj = serializer.Deserialize(stream); } T rsp = (T)obj; if (rsp != null) { rsp.Body = body; } return(rsp); }
internal static SoapReflectedMethod ReflectMethod(LogicalMethodInfo methodInfo, bool client, XmlReflectionImporter xmlImporter, SoapReflectionImporter soapImporter, string defaultNs) { SoapReflectedMethod method2; try { string str2; string str4; string key = methodInfo.GetKey(); SoapReflectedMethod method = new SoapReflectedMethod(); MethodAttribute attribute = new MethodAttribute(); object soapServiceAttribute = GetSoapServiceAttribute(methodInfo.DeclaringType); bool serviceDefaultIsEncoded = ServiceDefaultIsEncoded(soapServiceAttribute); object soapMethodAttribute = GetSoapMethodAttribute(methodInfo); if (soapMethodAttribute == null) { if (client) { return(null); } if (soapServiceAttribute is SoapRpcServiceAttribute) { SoapRpcMethodAttribute attribute2 = new SoapRpcMethodAttribute { Use = ((SoapRpcServiceAttribute)soapServiceAttribute).Use }; soapMethodAttribute = attribute2; } else if (soapServiceAttribute is SoapDocumentServiceAttribute) { SoapDocumentMethodAttribute attribute3 = new SoapDocumentMethodAttribute { Use = ((SoapDocumentServiceAttribute)soapServiceAttribute).Use }; soapMethodAttribute = attribute3; } else { soapMethodAttribute = new SoapDocumentMethodAttribute(); } } if (soapMethodAttribute is SoapRpcMethodAttribute) { SoapRpcMethodAttribute attribute4 = (SoapRpcMethodAttribute)soapMethodAttribute; method.rpc = true; method.use = attribute4.Use; method.oneWay = attribute4.OneWay; attribute.action = attribute4.Action; attribute.binding = attribute4.Binding; attribute.requestName = attribute4.RequestElementName; attribute.requestNs = attribute4.RequestNamespace; attribute.responseName = attribute4.ResponseElementName; attribute.responseNs = attribute4.ResponseNamespace; } else { SoapDocumentMethodAttribute attribute5 = (SoapDocumentMethodAttribute)soapMethodAttribute; method.rpc = false; method.use = attribute5.Use; method.paramStyle = attribute5.ParameterStyle; method.oneWay = attribute5.OneWay; attribute.action = attribute5.Action; attribute.binding = attribute5.Binding; attribute.requestName = attribute5.RequestElementName; attribute.requestNs = attribute5.RequestNamespace; attribute.responseName = attribute5.ResponseElementName; attribute.responseNs = attribute5.ResponseNamespace; if (method.use == SoapBindingUse.Default) { if (soapServiceAttribute is SoapDocumentServiceAttribute) { method.use = ((SoapDocumentServiceAttribute)soapServiceAttribute).Use; } if (method.use == SoapBindingUse.Default) { method.use = SoapBindingUse.Literal; } } if (method.paramStyle == SoapParameterStyle.Default) { if (soapServiceAttribute is SoapDocumentServiceAttribute) { method.paramStyle = ((SoapDocumentServiceAttribute)soapServiceAttribute).ParameterStyle; } if (method.paramStyle == SoapParameterStyle.Default) { method.paramStyle = SoapParameterStyle.Wrapped; } } } if (attribute.binding.Length > 0) { if (client) { throw new InvalidOperationException(System.Web.Services.Res.GetString("WebInvalidBindingPlacement", new object[] { soapMethodAttribute.GetType().Name })); } method.binding = WebServiceBindingReflector.GetAttribute(methodInfo, attribute.binding); } WebMethodAttribute methodAttribute = methodInfo.MethodAttribute; method.name = methodAttribute.MessageName; if (method.name.Length == 0) { method.name = methodInfo.Name; } if (method.rpc) { str2 = ((attribute.requestName.Length == 0) || !client) ? methodInfo.Name : attribute.requestName; } else { str2 = (attribute.requestName.Length == 0) ? method.name : attribute.requestName; } string requestNs = attribute.requestNs; if (requestNs == null) { if (((method.binding != null) && (method.binding.Namespace != null)) && (method.binding.Namespace.Length != 0)) { requestNs = method.binding.Namespace; } else { requestNs = defaultNs; } } if (method.rpc && (method.use != SoapBindingUse.Encoded)) { str4 = methodInfo.Name + "Response"; } else { str4 = (attribute.responseName.Length == 0) ? (method.name + "Response") : attribute.responseName; } string responseNs = attribute.responseNs; if (responseNs == null) { if (((method.binding != null) && (method.binding.Namespace != null)) && (method.binding.Namespace.Length != 0)) { responseNs = method.binding.Namespace; } else { responseNs = defaultNs; } } SoapParameterInfo[] infoArray = ReflectParameters(methodInfo.InParameters, requestNs); SoapParameterInfo[] infoArray2 = ReflectParameters(methodInfo.OutParameters, responseNs); method.action = attribute.action; if (method.action == null) { method.action = GetDefaultAction(defaultNs, methodInfo); } method.methodInfo = methodInfo; if (method.oneWay) { if (infoArray2.Length > 0) { throw new ArgumentException(System.Web.Services.Res.GetString("WebOneWayOutParameters"), "methodInfo"); } if (methodInfo.ReturnType != typeof(void)) { throw new ArgumentException(System.Web.Services.Res.GetString("WebOneWayReturnValue"), "methodInfo"); } } XmlReflectionMember[] members = new XmlReflectionMember[infoArray.Length]; for (int i = 0; i < members.Length; i++) { SoapParameterInfo info = infoArray[i]; XmlReflectionMember member = new XmlReflectionMember { MemberName = info.parameterInfo.Name, MemberType = info.parameterInfo.ParameterType }; if (member.MemberType.IsByRef) { member.MemberType = member.MemberType.GetElementType(); } member.XmlAttributes = info.xmlAttributes; member.SoapAttributes = info.soapAttributes; members[i] = member; } method.requestMappings = ImportMembersMapping(xmlImporter, soapImporter, serviceDefaultIsEncoded, method.rpc, method.use, method.paramStyle, str2, requestNs, attribute.requestNs == null, members, true, false, key, client); if (((GetSoapServiceRoutingStyle(soapServiceAttribute) == SoapServiceRoutingStyle.RequestElement) && (method.paramStyle == SoapParameterStyle.Bare)) && (method.requestMappings.Count != 1)) { throw new ArgumentException(System.Web.Services.Res.GetString("WhenUsingAMessageStyleOfParametersAsDocument0"), "methodInfo"); } string name = ""; string ns = ""; if (method.paramStyle == SoapParameterStyle.Bare) { if (method.requestMappings.Count == 1) { name = method.requestMappings[0].XsdElementName; ns = method.requestMappings[0].Namespace; } } else { name = method.requestMappings.XsdElementName; ns = method.requestMappings.Namespace; } method.requestElementName = new XmlQualifiedName(name, ns); if (!method.oneWay) { int num2 = infoArray2.Length; int num3 = 0; CodeIdentifiers identifiers = null; if (methodInfo.ReturnType != typeof(void)) { num2++; num3 = 1; identifiers = new CodeIdentifiers(); } members = new XmlReflectionMember[num2]; for (int m = 0; m < infoArray2.Length; m++) { SoapParameterInfo info2 = infoArray2[m]; XmlReflectionMember member2 = new XmlReflectionMember { MemberName = info2.parameterInfo.Name, MemberType = info2.parameterInfo.ParameterType }; if (member2.MemberType.IsByRef) { member2.MemberType = member2.MemberType.GetElementType(); } member2.XmlAttributes = info2.xmlAttributes; member2.SoapAttributes = info2.soapAttributes; members[num3++] = member2; if (identifiers != null) { identifiers.Add(member2.MemberName, null); } } if (methodInfo.ReturnType != typeof(void)) { XmlReflectionMember member3 = new XmlReflectionMember { MemberName = identifiers.MakeUnique(method.name + "Result"), MemberType = methodInfo.ReturnType, IsReturnValue = true, XmlAttributes = new XmlAttributes(methodInfo.ReturnTypeCustomAttributeProvider) }; member3.XmlAttributes.XmlRoot = null; member3.SoapAttributes = new SoapAttributes(methodInfo.ReturnTypeCustomAttributeProvider); members[0] = member3; } method.responseMappings = ImportMembersMapping(xmlImporter, soapImporter, serviceDefaultIsEncoded, method.rpc, method.use, method.paramStyle, str4, responseNs, attribute.responseNs == null, members, false, false, key + ":Response", !client); } SoapExtensionAttribute[] customAttributes = (SoapExtensionAttribute[])methodInfo.GetCustomAttributes(typeof(SoapExtensionAttribute)); method.extensions = new SoapReflectedExtension[customAttributes.Length]; for (int j = 0; j < customAttributes.Length; j++) { method.extensions[j] = new SoapReflectedExtension(customAttributes[j].ExtensionType, customAttributes[j]); } Array.Sort <SoapReflectedExtension>(method.extensions); SoapHeaderAttribute[] array = (SoapHeaderAttribute[])methodInfo.GetCustomAttributes(typeof(SoapHeaderAttribute)); Array.Sort(array, new SoapHeaderAttributeComparer()); Hashtable hashtable = new Hashtable(); method.headers = new SoapReflectedHeader[array.Length]; int num6 = 0; int length = method.headers.Length; ArrayList list = new ArrayList(); ArrayList list2 = new ArrayList(); for (int k = 0; k < method.headers.Length; k++) { SoapHeaderAttribute attribute7 = array[k]; SoapReflectedHeader header = new SoapReflectedHeader(); Type declaringType = methodInfo.DeclaringType; header.memberInfo = declaringType.GetField(attribute7.MemberName); if (header.memberInfo != null) { header.headerType = ((FieldInfo)header.memberInfo).FieldType; } else { header.memberInfo = declaringType.GetProperty(attribute7.MemberName); if (header.memberInfo == null) { throw HeaderException(attribute7.MemberName, methodInfo.DeclaringType, "WebHeaderMissing"); } header.headerType = ((PropertyInfo)header.memberInfo).PropertyType; } if (header.headerType.IsArray) { header.headerType = header.headerType.GetElementType(); header.repeats = true; if ((header.headerType != typeof(SoapUnknownHeader)) && (header.headerType != typeof(SoapHeader))) { throw HeaderException(attribute7.MemberName, methodInfo.DeclaringType, "WebHeaderType"); } } if (MemberHelper.IsStatic(header.memberInfo)) { throw HeaderException(attribute7.MemberName, methodInfo.DeclaringType, "WebHeaderStatic"); } if (!MemberHelper.CanRead(header.memberInfo)) { throw HeaderException(attribute7.MemberName, methodInfo.DeclaringType, "WebHeaderRead"); } if (!MemberHelper.CanWrite(header.memberInfo)) { throw HeaderException(attribute7.MemberName, methodInfo.DeclaringType, "WebHeaderWrite"); } if (!typeof(SoapHeader).IsAssignableFrom(header.headerType)) { throw HeaderException(attribute7.MemberName, methodInfo.DeclaringType, "WebHeaderType"); } SoapHeaderDirection direction = attribute7.Direction; if (method.oneWay && ((direction & (SoapHeaderDirection.Fault | SoapHeaderDirection.Out)) != 0)) { throw HeaderException(attribute7.MemberName, methodInfo.DeclaringType, "WebHeaderOneWayOut"); } if (hashtable.Contains(header.headerType)) { SoapHeaderDirection direction2 = (SoapHeaderDirection)hashtable[header.headerType]; if ((direction2 & direction) != 0) { throw HeaderException(attribute7.MemberName, methodInfo.DeclaringType, "WebMultiplyDeclaredHeaderTypes"); } hashtable[header.headerType] = direction | direction2; } else { hashtable[header.headerType] = direction; } if ((header.headerType != typeof(SoapHeader)) && (header.headerType != typeof(SoapUnknownHeader))) { XmlReflectionMember member4 = new XmlReflectionMember { MemberName = header.headerType.Name, MemberType = header.headerType }; XmlAttributes attributes = new XmlAttributes(header.headerType); if (attributes.XmlRoot != null) { member4.XmlAttributes = new XmlAttributes(); XmlElementAttribute attribute8 = new XmlElementAttribute { ElementName = attributes.XmlRoot.ElementName, Namespace = attributes.XmlRoot.Namespace }; member4.XmlAttributes.XmlElements.Add(attribute8); } member4.OverrideIsNullable = true; if ((direction & SoapHeaderDirection.In) != 0) { list.Add(member4); } if ((direction & (SoapHeaderDirection.Fault | SoapHeaderDirection.Out)) != 0) { list2.Add(member4); } header.custom = true; } header.direction = direction; if (!header.custom) { method.headers[--length] = header; } else { method.headers[num6++] = header; } } method.inHeaderMappings = ImportMembersMapping(xmlImporter, soapImporter, serviceDefaultIsEncoded, false, method.use, SoapParameterStyle.Bare, str2 + "InHeaders", defaultNs, true, (XmlReflectionMember[])list.ToArray(typeof(XmlReflectionMember)), false, true, key + ":InHeaders", client); if (!method.oneWay) { method.outHeaderMappings = ImportMembersMapping(xmlImporter, soapImporter, serviceDefaultIsEncoded, false, method.use, SoapParameterStyle.Bare, str4 + "OutHeaders", defaultNs, true, (XmlReflectionMember[])list2.ToArray(typeof(XmlReflectionMember)), false, true, key + ":OutHeaders", !client); } method2 = method; } catch (Exception exception) { if (((exception is ThreadAbortException) || (exception is StackOverflowException)) || (exception is OutOfMemoryException)) { throw; } throw new InvalidOperationException(System.Web.Services.Res.GetString("WebReflectionErrorMethod", new object[] { methodInfo.DeclaringType.Name, methodInfo.Name }), exception); } return(method2); }
// Methods public void Add(Type type, XmlAttributes attributes) { }
public static void AddOnly(this XmlAttributeOverrides xmlAttributeOverrides, System.Type type, string member, XmlAttributes attributes) { var customAttributes = type.GetProperty(member).GetCustomAttributes(typeof(XmlElementAttribute), false) as XmlElementAttribute[]; var xmlAttributes = new XmlAttributes { XmlAnyAttribute = attributes.XmlAnyAttribute, XmlArray = attributes.XmlArray, XmlAttribute = attributes.XmlAttribute, XmlDefaultValue = attributes.XmlDefaultValue, XmlEnum = attributes.XmlEnum, XmlIgnore = attributes.XmlIgnore, Xmlns = attributes.Xmlns, XmlRoot = attributes.XmlRoot, XmlText = attributes.XmlText, XmlType = attributes.XmlType }; var existingXmlElementAttributes = new List <XmlElementAttribute>(attributes.XmlElements.Count + customAttributes.Count()); existingXmlElementAttributes.AddRange(attributes.XmlElements.Cast <XmlElementAttribute>()); foreach (var customAttribute in customAttributes) { existingXmlElementAttributes.Add(customAttribute); } foreach (var xmlElementAttribute in existingXmlElementAttributes.Distinct(new XmlOverrider.XmlElementAttributeEqualityComparer())) { xmlAttributes.XmlElements.Add(xmlElementAttribute); } xmlAttributeOverrides.Add(type, member, xmlAttributes); }
public void Add(Type type, string member, XmlAttributes attributes);
public static void Add <T>(this XmlAttributeOverrides overrides, XmlAttributes attributes) { overrides.Add(typeof(T), attributes); }
private void RegisterMember(string name, XmlAttributes attributes) { overrides.Add(typeof(T), name, attributes); ignoredMembers.Remove(name); }
internal XmlReflectionMember(string name, Type type, XmlAttributes attributes) { memberName = name; memberType = type; xmlAttributes = attributes; }
private static XmlAttributes CreateElementAttributes(string @namespace) { var sertypeAttributes = new XmlAttributes { XmlElements = { new XmlElementAttribute("prim", typeof(PrimitiveType_v1)) { Namespace = @namespace }, new XmlElementAttribute("code", typeof(CodeType_v1)) { Namespace = @namespace }, new XmlElementAttribute("ptr", typeof(PointerType_v1)) { Namespace = @namespace }, new XmlElementAttribute("qual", typeof(QualifiedType_v1)) { Namespace = @namespace }, new XmlElementAttribute("arr", typeof(ArrayType_v1)) { Namespace = @namespace }, new XmlElementAttribute("enum", typeof(SerializedEnumType)) { Namespace = @namespace }, new XmlElementAttribute("str", typeof(StringType_v2)) { Namespace = @namespace }, new XmlElementAttribute("struct", typeof(StructType_v1)) { Namespace = @namespace }, new XmlElementAttribute("union", typeof(UnionType_v1)) { Namespace = @namespace }, new XmlElementAttribute("fn", typeof(SerializedSignature)) { Namespace = @namespace }, new XmlElementAttribute("typedef", typeof(SerializedTypedef)) { Namespace = @namespace }, new XmlElementAttribute("type", typeof(TypeReference_v1)) { Namespace = @namespace }, new XmlElementAttribute("void", typeof(VoidType_v1)) { Namespace = @namespace }, } }; return(sertypeAttributes); }
public static ShaderWindowSettings LoadConfiguration(out DialogResult result) { if (!File.Exists(ShaderManager.DefaultConfigurationFile)) { result = DialogResult.OK; return(new ShaderWindowSettings()); } var olderVersion = false; using (var reader = XmlReader.Create(ShaderManager.DefaultConfigurationFile)) { olderVersion = reader.ReadToDescendant("ShaderConfiguration") && reader.AttributeCount == 0; } if (olderVersion) { result = MessageBox.Show( Resources.ConfigurationFileUpgrade_Message, Resources.ConfigurationFileUpgrade_Caption, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning); if (result == DialogResult.Cancel) { return(null); } var overrides = new XmlAttributeOverrides(); var shaderAttributes = new XmlAttributes(); var materialElement = new XmlArrayItemAttribute(); materialElement.ElementName = "ShaderConfiguration"; materialElement.Type = typeof(MaterialConfiguration); shaderAttributes.XmlArrayItems.Add(materialElement); overrides.Add(typeof(ShaderWindowSettings), "Shaders", shaderAttributes); var bufferBindingAttributes = new XmlAttributes(); var textureBindingElement = new XmlArrayItemAttribute(); textureBindingElement.ElementName = "TextureBindingConfiguration"; textureBindingElement.Type = typeof(TextureBindingConfiguration); bufferBindingAttributes.XmlArray = new XmlArrayAttribute("TextureBindings"); bufferBindingAttributes.XmlArrayItems.Add(textureBindingElement); overrides.Add(typeof(ShaderConfiguration), "BufferBindings", bufferBindingAttributes); ShaderWindowSettings configuration; var serializer = new XmlSerializer(typeof(ShaderWindowSettings), overrides); using (var reader = XmlReader.Create(ShaderManager.DefaultConfigurationFile)) { configuration = (ShaderWindowSettings)serializer.Deserialize(reader); } if (result == DialogResult.Yes) { ShaderManager.SaveConfiguration(configuration); } else { return(configuration); } } result = DialogResult.OK; try { return(ShaderManager.LoadConfiguration()); } catch { result = DialogResult.Cancel; throw; } }
private bool FillRecord(object rec, Tuple <long, XElement> pair) { long lineNo; XElement node; lineNo = pair.Item1; node = pair.Item2; fXElements = null; fieldValue = null; fieldConfig = null; pi = null; xpn = node.CreateNavigator(Configuration.NamespaceManager.NameTable); ToDictionary(node); foreach (KeyValuePair <string, ChoXmlRecordFieldConfiguration> kvp in Configuration.RecordFieldConfigurationsDict) { fieldValue = null; fieldConfig = kvp.Value; if (Configuration.PIDict != null) { Configuration.PIDict.TryGetValue(kvp.Key, out pi); } if (fieldConfig.XPath == "text()") { if (Configuration.GetNameWithNamespace(node.Name) == fieldConfig.FieldName) { object value = node; if (!RaiseBeforeRecordFieldLoad(rec, pair.Item1, kvp.Key, ref value)) { continue; } if (fieldConfig.ValueConverter != null) { value = fieldConfig.ValueConverter(value); } fieldValue = value is XElement ? node.Value : value; } else if (Configuration.ColumnCountStrict) { throw new ChoParserException("Missing '{0}' xml node.".FormatString(fieldConfig.FieldName)); } } else { if (/*!fieldConfig.UseCache && */ !xDict.ContainsKey(fieldConfig.FieldName)) { xNodes.Clear(); foreach (XPathNavigator z in xpn.Select(fieldConfig.XPath, Configuration.NamespaceManager)) { xNodes.Add(z.UnderlyingObject); } object value = xNodes; if (!RaiseBeforeRecordFieldLoad(rec, pair.Item1, kvp.Key, ref value)) { continue; } if (fieldConfig.ValueConverter != null) { fieldValue = fieldConfig.ValueConverter(value); } else { //object[] xNodes = ((IEnumerable)node.XPathEvaluate(fieldConfig.XPath, Configuration.NamespaceManager)).OfType<object>().ToArray(); //continue; XAttribute fXAttribute = xNodes.OfType <XAttribute>().FirstOrDefault(); if (fXAttribute != null) { fieldValue = fXAttribute.Value; } else { fXElements = xNodes.OfType <XElement>().ToArray(); if (fXElements != null) { if (Configuration.IsDynamicObject) { if (fieldConfig.IsArray != null && fieldConfig.IsArray.Value) { List <object> list = new List <object>(); foreach (var ele in fXElements) { if (fieldConfig.FieldType.IsSimple()) { list.Add(ChoConvert.ConvertTo(ele.Value, fieldConfig.FieldType.GetItemType())); } else { list.Add(ele.GetOuterXml().ToObjectFromXml(fieldConfig.FieldType.GetItemType())); } } fieldValue = list.ToArray(); } else { if (fieldConfig.FieldType == typeof(string) || fieldConfig.FieldType.IsSimple()) { XElement fXElement = fXElements.FirstOrDefault(); if (fXElement != null) { fieldValue = fXElement.Value; } } else { XmlAttributeOverrides overrides = null; var xattribs = new XmlAttributes(); var xroot = new XmlRootAttribute(fieldConfig.FieldName); xattribs.XmlRoot = xroot; overrides = new XmlAttributeOverrides(); overrides.Add(fieldConfig.FieldType, xattribs); XElement fXElement = fXElements.FirstOrDefault(); if (fXElement != null) { fieldValue = fXElement.GetOuterXml().ToObjectFromXml(fieldConfig.FieldType, overrides); } } } } else { XmlAttributeOverrides overrides = null; var xattribs = new XmlAttributes(); var xroot = new XmlRootAttribute(fieldConfig.FieldName); xattribs.XmlRoot = xroot; overrides = new XmlAttributeOverrides(); overrides.Add(fieldConfig.FieldType, xattribs); XElement fXElement = fXElements.FirstOrDefault(); if (fXElement != null) { fieldValue = fXElement.GetOuterXml().ToObjectFromXml(fieldConfig.FieldType, overrides); } } } else if (Configuration.ColumnCountStrict) { throw new ChoParserException("Missing '{0}' xml node.".FormatString(fieldConfig.FieldName)); } } } } else { if (xDict[fieldConfig.FieldName].Count == 1) { fieldValue = xDict[fieldConfig.FieldName][0]; } else { fieldValue = xDict[fieldConfig.FieldName]; } if (!RaiseBeforeRecordFieldLoad(rec, pair.Item1, kvp.Key, ref fieldValue)) { continue; } if (fieldConfig.ValueConverter != null) { fieldValue = fieldConfig.ValueConverter(fieldValue); } } } if (Configuration.IsDynamicObject) { if (kvp.Value.FieldType == null) { kvp.Value.FieldType = fieldValue is ICollection ? typeof(string[]) : DiscoverFieldType(fieldValue as string); } } else { if (pi != null) { kvp.Value.FieldType = pi.PropertyType; } else { kvp.Value.FieldType = typeof(string); } } if (fieldValue is string) { fieldValue = CleanFieldValue(fieldConfig, kvp.Value.FieldType, fieldValue as string); } try { bool ignoreFieldValue = fieldConfig.IgnoreFieldValue(fieldValue); if (ignoreFieldValue) { fieldValue = fieldConfig.IsDefaultValueSpecified ? fieldConfig.DefaultValue : null; } if (Configuration.IsDynamicObject) { var dict = rec as IDictionary <string, Object>; if (!fieldConfig.IsArray.CastTo <bool>()) { dict.ConvertNSetMemberValue(kvp.Key, kvp.Value, ref fieldValue, Configuration.Culture); } else { dict[kvp.Key] = fieldValue; } if ((Configuration.ObjectValidationMode & ChoObjectValidationMode.MemberLevel) == ChoObjectValidationMode.MemberLevel) { dict.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode); } } else { if (pi != null) { rec.ConvertNSetMemberValue(kvp.Key, kvp.Value, ref fieldValue, Configuration.Culture); } else { throw new ChoMissingRecordFieldException("Missing '{0}' property in {1} type.".FormatString(kvp.Key, ChoType.GetTypeName(rec))); } if ((Configuration.ObjectValidationMode & ChoObjectValidationMode.MemberLevel) == ChoObjectValidationMode.MemberLevel) { rec.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode); } } if (!RaiseAfterRecordFieldLoad(rec, pair.Item1, kvp.Key, fieldValue)) { return(false); } } catch (ChoParserException) { throw; } catch (ChoMissingRecordFieldException) { if (Configuration.ThrowAndStopOnMissingField) { throw; } } catch (Exception ex) { ChoETLFramework.HandleException(ex); if (fieldConfig.ErrorMode == ChoErrorMode.ThrowAndStop) { throw; } try { if (Configuration.IsDynamicObject) { var dict = rec as IDictionary <string, Object>; if (dict.SetFallbackValue(kvp.Key, kvp.Value, Configuration.Culture, ref fieldValue)) { dict.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode); } else if (dict.SetDefaultValue(kvp.Key, kvp.Value, Configuration.Culture)) { dict.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode); } else { throw new ChoReaderException($"Failed to parse '{fieldValue}' value for '{fieldConfig.FieldName}' field.", ex); } } else if (pi != null) { if (rec.SetFallbackValue(kvp.Key, kvp.Value, Configuration.Culture)) { rec.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode); } else if (rec.SetDefaultValue(kvp.Key, kvp.Value, Configuration.Culture)) { rec.DoMemberLevelValidation(kvp.Key, kvp.Value, Configuration.ObjectValidationMode); } else { throw new ChoReaderException($"Failed to parse '{fieldValue}' value for '{fieldConfig.FieldName}' field.", ex); } } else { throw new ChoReaderException($"Failed to parse '{fieldValue}' value for '{fieldConfig.FieldName}' field.", ex); } } catch (Exception innerEx) { if (ex == innerEx.InnerException) { if (fieldConfig.ErrorMode == ChoErrorMode.IgnoreAndContinue) { continue; } else { if (!RaiseRecordFieldLoadError(rec, pair.Item1, kvp.Key, fieldValue, ex)) { throw new ChoReaderException($"Failed to parse '{fieldValue}' value for '{fieldConfig.FieldName}' field.", ex); } } } else { throw new ChoReaderException("Failed to assign '{0}' fallback value to '{1}' field.".FormatString(fieldValue, fieldConfig.FieldName), innerEx); } } } } return(true); }
private void ReadStructContent(object obj, StructMapping mapping) { this.m_reader.MoveToContent(); string name = this.m_reader.Name; string namespaceURI = this.m_reader.NamespaceURI; this.ReadStructAttributes(obj, mapping); if (this.m_reader.IsEmptyElement) { this.m_reader.Skip(); } else { this.m_reader.ReadStartElement(); this.m_reader.MoveToContent(); while (this.m_reader.NodeType != XmlNodeType.EndElement && this.m_reader.NodeType != 0) { string localName = this.m_reader.LocalName; string namespaceURI2 = this.m_reader.NamespaceURI; namespaceURI2 = ((namespaceURI == namespaceURI2) ? string.Empty : namespaceURI2); MemberMapping memberMapping = mapping.GetElement(localName, namespaceURI2); Type type = null; if (memberMapping != null) { type = memberMapping.Type; } else { List <MemberMapping> typeNameElements = mapping.GetTypeNameElements(); if (typeNameElements != null) { bool flag = false; for (int i = 0; i < typeNameElements.Count; i++) { memberMapping = typeNameElements[i]; XmlElementAttributes xmlElements = memberMapping.XmlAttributes.XmlElements; if (base.XmlOverrides != null) { XmlAttributes xmlAttributes = base.XmlOverrides[obj.GetType()]; if (xmlAttributes == null) { xmlAttributes = base.XmlOverrides[memberMapping.Type]; } if (xmlAttributes != null && xmlAttributes.XmlElements != null) { xmlElements = xmlAttributes.XmlElements; } } foreach (XmlElementAttribute item in xmlElements) { if (item.ElementName == localName && item.Type != null) { type = item.Type; flag = true; break; } } if (flag) { break; } } } } if (type != null) { if (memberMapping.ChildAttributes != null) { foreach (MemberMapping childAttribute in memberMapping.ChildAttributes) { this.ReadChildAttribute(obj, mapping, childAttribute); } } if (memberMapping.IsReadOnly) { if (!TypeMapper.IsPrimitiveType(type)) { object value = memberMapping.GetValue(obj); if (value != null) { this.ReadObjectContent(value, memberMapping, 0); } else { this.m_reader.Skip(); } } else { this.m_reader.Skip(); } } else { object obj2 = this.ReadObject(type, memberMapping, 0); if (obj2 != null) { memberMapping.SetValue(obj, obj2); } } } else { if (namespaceURI2 != string.Empty && this.m_validNamespaces.Contains(namespaceURI2)) { IXmlLineInfo xmlLineInfo = (IXmlLineInfo)this.m_reader; string message = RDLValidatingReaderStrings.rdlValidationInvalidMicroVersionedElement(this.m_reader.Name, name, xmlLineInfo.LineNumber.ToString(CultureInfo.InvariantCulture.NumberFormat), xmlLineInfo.LinePosition.ToString(CultureInfo.InvariantCulture.NumberFormat)); throw new XmlException(message); } this.m_reader.Skip(); } this.m_reader.MoveToContent(); } this.m_reader.ReadEndElement(); } }
public static void Add <T>(this XmlAttributeOverrides overrides, Expression <Func <T, object> > propertySelector, XmlAttributes attributes) { overrides.Add(typeof(T), propertySelector.GetPropertyName(), attributes); }
public T Parse <T>(string body) where T : TopResponse { Type type = typeof(T); string rootTagName = GetRootElement(body); string key = type.FullName; if (Constants.ERROR_RESPONSE.Equals(rootTagName)) { key += ("_" + Constants.ERROR_RESPONSE); } XmlSerializer serializer = null; bool incl = false; rwLock.AcquireReaderLock(50); try { if (rwLock.IsReaderLockHeld) { incl = parsers.TryGetValue(key, out serializer); } } finally { if (rwLock.IsReaderLockHeld) { rwLock.ReleaseReaderLock(); } } if (!incl || serializer == null) { XmlAttributes rootAttrs = new XmlAttributes(); rootAttrs.XmlRoot = new XmlRootAttribute(rootTagName); XmlAttributeOverrides attrOvrs = new XmlAttributeOverrides(); attrOvrs.Add(type, rootAttrs); serializer = new XmlSerializer(type, attrOvrs); rwLock.AcquireWriterLock(50); try { if (rwLock.IsWriterLockHeld) { parsers[key] = serializer; } } finally { if (rwLock.IsWriterLockHeld) { rwLock.ReleaseWriterLock(); } } } object obj = null; using (System.IO.Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(body))) { obj = serializer.Deserialize(stream); } T rsp = (T)obj; if (rsp != null) { rsp.Body = body; } return(rsp); }
/// <summary> /// 序列化类到xml文档 /// </summary> /// <typeparam name="T">类</typeparam> /// <param name="para">类的对象</param> /// <param name="filePath">xml文档路径(包含文件名)</param> /// <returns>成功:true,失败:false</returns> public static bool XMLWriteToFile(List <FigureBaseModel> figures, string filePath, Type[] types = null) { try { XmlWriter writer = null; //声明一个xml编写器 XmlWriterSettings writerSetting = new XmlWriterSettings { Indent = true, //定义xml格式,自动创建新的行 Encoding = UTF8Encoding.UTF8, //编码格式 }; writer = XmlWriter.Create(filePath, writerSetting); XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides(); XmlAttributes attrs = new XmlAttributes(); XmlElementAttribute attrArc = new XmlElementAttribute(); attrArc.ElementName = "Arc"; attrArc.Type = typeof(ArcModel); XmlElementAttribute attrCircle = new XmlElementAttribute(); attrCircle.ElementName = "Circle"; attrCircle.Type = typeof(CircleModel); XmlElementAttribute attrEllipse = new XmlElementAttribute(); attrEllipse.ElementName = "Ellipse"; attrEllipse.Type = typeof(EllipseModel); XmlElementAttribute attrLwPolyline = new XmlElementAttribute(); attrLwPolyline.ElementName = "LwPolyline"; attrLwPolyline.Type = typeof(LwPolylineModel); XmlElementAttribute attrPoint = new XmlElementAttribute(); attrPoint.ElementName = "Point"; attrPoint.Type = typeof(PointModel); XmlElementAttribute attrPolyBezier = new XmlElementAttribute(); attrPolyBezier.ElementName = "PolyBezier"; attrPolyBezier.Type = typeof(PolyBezierModel); // Add the XmlElementAttribute to the collection of objects. attrs.XmlElements.Add(attrArc); attrs.XmlElements.Add(attrCircle); attrs.XmlElements.Add(attrEllipse); attrs.XmlElements.Add(attrLwPolyline); attrs.XmlElements.Add(attrPoint); attrs.XmlElements.Add(attrPolyBezier); attrOverrides.Add(typeof(Entities), "Figures", attrs); WXFDocument fgs = new WXFDocument() { Entities = new Entities() { Figures = figures } }; XmlSerializer xser = new XmlSerializer(typeof(WXFDocument), attrOverrides); //实例化序列化对象 xser.Serialize(writer, fgs); //序列化对象到xml文档 writer.Close(); } catch (Exception ex) { LogUtil.Instance.Error(ex.Message); return(false); } return(true); }
/// <summary> /// Loops to the inheritance chain of an object, takes xml attributes from base /// objects and applies the overrides to the derived object /// </summary> /// <param name="baseType"></param> /// <param name="derivedType"></param> /// <param name="overrides"></param> public static void AddAttributeOverrides(Type baseType, Type derivedType, XmlAttributeOverrides overrides) { //loop, starting with derived type Type type = derivedType; do { //override attributes detected the next basetype type = type.BaseType; if (type == null) { break; } PropertyInfo[] props = baseType.GetProperties(); foreach (PropertyInfo pi in props) { //do not override attribute again if it already has override XmlAttributes overrideAttributes = overrides[derivedType, pi.Name]; if (overrideAttributes == null) { Object[] attributes = pi.GetCustomAttributes(true); foreach (Object a in attributes) { XmlAttributes attrs = new XmlAttributes(); if (a is XmlAttributeAttribute) { attrs.XmlAttribute = a as XmlAttributeAttribute; } else if (a is XmlElementAttribute) { attrs.XmlElements.Add(a as XmlElementAttribute); } else if (a is XmlIgnoreAttribute) { attrs.XmlIgnore = true; } else if (a is XmlArrayAttribute) { attrs.XmlArray = a as XmlArrayAttribute; } else if (a is XmlArrayItemAttribute) { attrs.XmlArrayItems.Add(a as XmlArrayItemAttribute); } else { continue; } bool exist = false; // first check if attribute does not exist // iterate over all properties because there can be property which hides type of the base class PropertyInfo[] properties = derivedType.GetProperties(); foreach (PropertyInfo pi2 in properties) { if (pi2.Name == pi.Name && pi2.Name != "Item") { Object[] attrs2 = derivedType.GetProperty(pi2.Name, pi2.PropertyType).GetCustomAttributes(false); foreach (Object a2 in attrs2) { if (a2.Equals(a)) { exist = true; } } } } if (!exist) // override { overrides.Add(derivedType, pi.Name, attrs); } } } } } while (!type.Equals(baseType)); }
private static bool HasNoXmlParameterAttributes(XmlAttributes xmlAttributes) { return((((xmlAttributes.XmlAnyAttribute == null) && ((xmlAttributes.XmlAnyElements == null) || (xmlAttributes.XmlAnyElements.Count == 0))) && ((((xmlAttributes.XmlArray == null) && (xmlAttributes.XmlAttribute == null)) && (!xmlAttributes.XmlIgnore && (xmlAttributes.XmlText == null))) && ((xmlAttributes.XmlChoiceIdentifier == null) && ((xmlAttributes.XmlElements == null) || (xmlAttributes.XmlElements.Count == 0))))) && !xmlAttributes.Xmlns); }
public void Add(Type type, XmlAttributes attributes);
internal XmlReflectionMember (string name, Type type, XmlAttributes attributes) { memberName = name; memberType = type; xmlAttributes = attributes; }
/// <summary> /// Loads and parses the given RICO file. /// </summary> /// <param name="ricoDefPath">Definition file path</param> /// <param name="isLocal">True if this is a local settings file, false for author settings file</param> /// <returns>Parsed Ploppable RICO definition file</returns> public static PloppableRICODefinition ParseRICODefinition(string ricoDefPath, bool isLocal = false) { // Local settings flag. string localOrAuthor = isLocal ? "local" : "author"; try { // Open file. using (StreamReader reader = new StreamReader(ricoDefPath)) { // Create new XML (de)serializer XmlAttributes attrs = new XmlAttributes(); XmlElementAttribute attr = new XmlElementAttribute { ElementName = "RICOBuilding", Type = typeof(RICOBuilding) }; XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides(); attrOverrides.Add(typeof(RICOBuilding), "Building", attrs); // Read XML. XmlSerializer xmlSerializer = new XmlSerializer(typeof(PloppableRICODefinition), attrOverrides); PloppableRICODefinition result = xmlSerializer.Deserialize(reader) as PloppableRICODefinition; StringBuilder errorList; if (result.Buildings.Count == 0) { Logging.Message("no parseable buildings in ", localOrAuthor, " XML settings file at ", ricoDefPath); } else { foreach (RICOBuilding building in result.Buildings) { // Check for fatal errors in each building. errorList = building.FatalErrors; if (errorList.Length == 0) { // No fatal errors; check for non-fatal errors. errorList = building.NonFatalErrors; if (errorList.Length != 0) { if (isLocal && building.ricoEnabled) { // Errors in local settings need to be reported, except for buildings that aren't activated in RICO (e.g. for when the user has de-activated a RICO builidng with issues). Logging.Error("non-fatal errors for building '", building.Name, "' in local settings:\r\n", errorList); } else { // Errors in other settings should be logged if verbose logging is enabled, but otherwise continue. Logging.Message("non-fatal errors for building '", building.Name, "' in author settings:\r\n", errorList); } } } else { // Fatal errors! Need to be reported direct to user and the building ignored. Logging.Error("fatal errors for building '", building.Name, "' in ", localOrAuthor, " settings:\r\n", errorList); } } } reader.Close(); return(result); } } catch (Exception e) { Logging.LogException(e, "Unexpected Exception while deserializing ", localOrAuthor, " RICO file at ", ricoDefPath); return(null); } }
public XmlAttributeOverride(Type type, string member, XmlAttributes attributes) { Type = type; Member = member; Attributes = attributes; }
public void Add(Type type, string member, XmlAttributes attributes) { }
internal static void LoadXmlFormatExtensions(Type[] extensionTypes, XmlAttributeOverrides overrides, XmlSerializerNamespaces namespaces) { Hashtable table = new Hashtable(); table.Add(typeof(ServiceDescription), new XmlAttributes()); table.Add(typeof(Import), new XmlAttributes()); table.Add(typeof(Port), new XmlAttributes()); table.Add(typeof(Service), new XmlAttributes()); table.Add(typeof(FaultBinding), new XmlAttributes()); table.Add(typeof(InputBinding), new XmlAttributes()); table.Add(typeof(OutputBinding), new XmlAttributes()); table.Add(typeof(OperationBinding), new XmlAttributes()); table.Add(typeof(Binding), new XmlAttributes()); table.Add(typeof(OperationFault), new XmlAttributes()); table.Add(typeof(OperationInput), new XmlAttributes()); table.Add(typeof(OperationOutput), new XmlAttributes()); table.Add(typeof(Operation), new XmlAttributes()); table.Add(typeof(PortType), new XmlAttributes()); table.Add(typeof(Message), new XmlAttributes()); table.Add(typeof(MessagePart), new XmlAttributes()); table.Add(typeof(Types), new XmlAttributes()); Hashtable extensions = new Hashtable(); foreach (Type extensionType in extensionTypes) { if (extensions[extensionType] != null) { continue; } extensions.Add(extensionType, extensionType); object[] attrs = extensionType.GetCustomAttributes(typeof(XmlFormatExtensionAttribute), false); if (attrs.Length == 0) { throw new ArgumentException(SR.Format(SR.RequiredXmlFormatExtensionAttributeIsMissing1, extensionType.FullName), nameof(extensionTypes)); } XmlFormatExtensionAttribute extensionAttr = (XmlFormatExtensionAttribute)attrs[0]; foreach (Type extensionPointType in extensionAttr.ExtensionPoints) { XmlAttributes xmlAttrs = (XmlAttributes)table[extensionPointType]; if (xmlAttrs == null) { xmlAttrs = new XmlAttributes(); table.Add(extensionPointType, xmlAttrs); } XmlElementAttribute xmlAttr = new XmlElementAttribute(extensionAttr.ElementName, extensionType); xmlAttr.Namespace = extensionAttr.Namespace; xmlAttrs.XmlElements.Add(xmlAttr); } attrs = extensionType.GetCustomAttributes(typeof(XmlFormatExtensionPrefixAttribute), false); string[] prefixes = new string[attrs.Length]; Hashtable nsDefs = new Hashtable(); for (int i = 0; i < attrs.Length; i++) { XmlFormatExtensionPrefixAttribute prefixAttr = (XmlFormatExtensionPrefixAttribute)attrs[i]; prefixes[i] = prefixAttr.Prefix; nsDefs.Add(prefixAttr.Prefix, prefixAttr.Namespace); } Array.Sort(prefixes, InvariantComparer.Default); for (int i = 0; i < prefixes.Length; i++) { namespaces.Add(prefixes[i], (string)nsDefs[prefixes[i]]); } } foreach (Type extensionPointType in table.Keys) { XmlFormatExtensionPointAttribute attr = GetExtensionPointAttribute(extensionPointType); XmlAttributes xmlAttrs = (XmlAttributes)table[extensionPointType]; if (attr.AllowElements) { xmlAttrs.XmlAnyElements.Add(new XmlAnyElementAttribute()); } overrides.Add(extensionPointType, attr.MemberName, xmlAttrs); } }
/// <summary> /// Инициализация переопределенных тегов для класса In1Card /// </summary> private static void GetElementAttributeIn1Card() { var myElementAttribute = new XmlElementAttribute("IN1.1") { Order = 0 }; var myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(In1Card), "Id", myAttributes); myElementAttribute = new XmlElementAttribute { ElementName = "IN1.2", Order = 1 }; myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(In1Card), "PlanId", myAttributes); myElementAttribute = new XmlElementAttribute { ElementName = "IN1.3", Order = 2 }; myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(In1Card), "CompanyId", myAttributes); myElementAttribute = new XmlElementAttribute { ElementName = "IN1.4", Order = 3 }; myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(In1Card), "CompanyName", myAttributes); myElementAttribute = new XmlElementAttribute { ElementName = "IN1.5", Order = 4 }; myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(In1Card), "AddressSmo", myAttributes); myElementAttribute = new XmlElementAttribute { ElementName = "IN1.6", Order = 5 }; myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(In1Card), "FioInSmo", myAttributes); myElementAttribute = new XmlElementAttribute { ElementName = "IN1.7", Order = 6 }; myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(In1Card), "Phone", myAttributes); myElementAttribute = new XmlElementAttribute { ElementName = "IN1.12", Order = 7 }; myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(In1Card), "DateBeginInsurence", myAttributes); myElementAttribute = new XmlElementAttribute { ElementName = "IN1.13", Order = 8 }; myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(In1Card), "DateEndInsurence", myAttributes); myElementAttribute = new XmlElementAttribute { ElementName = "IN1.15", Order = 9 }; myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(In1Card), "CodeOfRegion", myAttributes); myElementAttribute = new XmlElementAttribute { ElementName = "IN1.16", Order = 10 }; myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(In1Card), "FioList", myAttributes); myElementAttribute = new XmlElementAttribute { ElementName = "IN1.18", Order = 11 }; myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(In1Card), "BirthDay", myAttributes); myElementAttribute = new XmlElementAttribute { ElementName = "IN1.19", Order = 12 }; myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(In1Card), "AddressList", myAttributes); myElementAttribute = new XmlElementAttribute { ElementName = "IN1.35", Order = 13 }; myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(In1Card), "InsuranceType", myAttributes); myElementAttribute = new XmlElementAttribute { ElementName = "IN1.36", Order = 14 }; myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(In1Card), "InsuranceSerNum", myAttributes); myElementAttribute = new XmlElementAttribute { ElementName = "IN1.42", Order = 15 }; myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(In1Card), "Employment", myAttributes); myElementAttribute = new XmlElementAttribute { ElementName = "IN1.43", Order = 16 }; myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(In1Card), "Sex", myAttributes); myElementAttribute = new XmlElementAttribute { ElementName = "IN1.49", Order = 17 }; myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(In1Card), "IdentificatorsList", myAttributes); myElementAttribute = new XmlElementAttribute { ElementName = "IN1.52", Order = 18 }; myAttributes = new XmlAttributes(); myAttributes.XmlElements.Add(myElementAttribute); myOverrides.Add(typeof(In1Card), "PlaceOfBirth", myAttributes); }
/// <summary> /// Loads OtterEditor Plugins /// </summary> private static void LoadPlugins() { List <Type> controlTypes = new List <Type>(); List <Type> layoutTypes = new List <Type>(); controlTypes.Add(typeof(Otter.UI.GUIButton)); controlTypes.Add(typeof(Otter.UI.GUISprite)); controlTypes.Add(typeof(Otter.UI.GUILabel)); controlTypes.Add(typeof(Otter.UI.GUITable)); controlTypes.Add(typeof(Otter.UI.GUIToggle)); controlTypes.Add(typeof(Otter.UI.GUISlider)); controlTypes.Add(typeof(Otter.UI.GUIMask)); controlTypes.Add(typeof(Otter.UI.GUIGroup)); layoutTypes.Add(typeof(Otter.UI.ControlLayout)); layoutTypes.Add(typeof(Otter.UI.ButtonLayout)); layoutTypes.Add(typeof(Otter.UI.SpriteLayout)); layoutTypes.Add(typeof(Otter.UI.LabelLayout)); layoutTypes.Add(typeof(Otter.UI.TableLayout)); layoutTypes.Add(typeof(Otter.UI.ToggleLayout)); layoutTypes.Add(typeof(Otter.UI.SliderLayout)); layoutTypes.Add(typeof(Otter.UI.MaskLayout)); layoutTypes.Add(typeof(Otter.UI.GroupLayout)); try { // Let's see if we can find plugins string[] files = System.IO.Directory.GetFiles(Application.StartupPath + "\\Plugins"); foreach (string file in files) { try { System.Console.WriteLine("File: " + file); System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFile(file); Type[] types = assembly.GetTypes(); foreach (Type type in types) { if (type.IsSubclassOf(typeof(IPlugin))) { PluginAttribute attribute = (PluginAttribute)System.Attribute.GetCustomAttribute(type, typeof(PluginAttribute)); if (attribute != null) { Globals.Plugins.Add(type); } } else if (!controlTypes.Contains(type) && type.IsSubclassOf(typeof(Otter.UI.GUIControl))) { // Found a custom GUIControl. Ensure that the "ControlAttribute" is present System.Attribute attribute = System.Attribute.GetCustomAttribute(type, typeof(ControlAttribute)); if (attribute != null) { Globals.CustomControlTypes.Add(type); controlTypes.Add(type); } } else if (!layoutTypes.Contains(type) && type.IsSubclassOf(typeof(Otter.UI.ControlLayout))) { layoutTypes.Add(type); } } } catch (Exception) { } } } catch (Exception) { } // TODO - Attempt to serialize/deserialize each type before // it's added to the controls list. If it fails, don't add it. XmlAttributes controlAttrs = new XmlAttributes(); foreach (Type type in controlTypes) { controlAttrs.XmlArrayItems.Add(new XmlArrayItemAttribute(type)); } GUIProject.XmlAttributeOverrides.Add(typeof(Otter.UI.GUIControl), "Controls", controlAttrs); XmlAttributes layoutAttrs = new XmlAttributes(); foreach (Type type in layoutTypes) { layoutAttrs.XmlElements.Add(new XmlElementAttribute(type)); } GUIProject.XmlAttributeOverrides.Add(typeof(Otter.UI.GUIControl), "Layout", layoutAttrs); GUIProject.XmlAttributeOverrides.Add(typeof(Otter.UI.Animation.KeyFrame), "Layout", layoutAttrs); }
/// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Add(Type type, XmlAttributes attributes) { Add(type, string.Empty, attributes); }
private static XmlAttributeOverrides GenerateMzIdentMlOverrides(string namespaceUrl) { // root override: affects only MzIdentMLType //[System.Xml.Serialization.XmlRootAttribute("MzIdentML", Namespace = "http://psidev.info/psi/pi/mzIdentML/1.1", IsNullable = false)] // all: //[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://psidev.info/psi/pi/mzIdentML/1.1")] var xmlOverrides = new XmlAttributeOverrides(); var xmlTypeNsOverride = new XmlAttributes(); var xmlTypeNs = new XmlTypeAttribute { Namespace = namespaceUrl }; xmlTypeNsOverride.XmlType = xmlTypeNs; var xmlRootOverrides = new XmlAttributes { XmlType = xmlTypeNs }; var xmlRootOverride = new XmlRootAttribute { ElementName = "MzIdentML", Namespace = namespaceUrl, IsNullable = false }; xmlRootOverrides.XmlRoot = xmlRootOverride; xmlOverrides.Add(typeof(MzIdentMLType), xmlRootOverrides); xmlOverrides.Add(typeof(cvType), xmlTypeNsOverride); xmlOverrides.Add(typeof(SpectrumIdentificationItemRefType), xmlTypeNsOverride); xmlOverrides.Add(typeof(PeptideHypothesisType), xmlTypeNsOverride); xmlOverrides.Add(typeof(FragmentArrayType), xmlTypeNsOverride); xmlOverrides.Add(typeof(IonTypeType), xmlTypeNsOverride); xmlOverrides.Add(typeof(CVParamType), xmlTypeNsOverride); xmlOverrides.Add(typeof(UserParamType), xmlTypeNsOverride); xmlOverrides.Add(typeof(ParamType), xmlTypeNsOverride); xmlOverrides.Add(typeof(ParamListType), xmlTypeNsOverride); xmlOverrides.Add(typeof(PeptideEvidenceRefType), xmlTypeNsOverride); xmlOverrides.Add(typeof(AnalysisDataType), xmlTypeNsOverride); xmlOverrides.Add(typeof(SpectrumIdentificationListType), xmlTypeNsOverride); xmlOverrides.Add(typeof(MeasureType), xmlTypeNsOverride); xmlOverrides.Add(typeof(IdentifiableType), xmlTypeNsOverride); xmlOverrides.Add(typeof(BibliographicReferenceType), xmlTypeNsOverride); xmlOverrides.Add(typeof(ProteinDetectionHypothesisType), xmlTypeNsOverride); xmlOverrides.Add(typeof(ProteinAmbiguityGroupType), xmlTypeNsOverride); xmlOverrides.Add(typeof(ProteinDetectionListType), xmlTypeNsOverride); xmlOverrides.Add(typeof(SpectrumIdentificationItemType), xmlTypeNsOverride); xmlOverrides.Add(typeof(SpectrumIdentificationResultType), xmlTypeNsOverride); xmlOverrides.Add(typeof(ExternalDataType), xmlTypeNsOverride); xmlOverrides.Add(typeof(FileFormatType), xmlTypeNsOverride); xmlOverrides.Add(typeof(SpectraDataType), xmlTypeNsOverride); xmlOverrides.Add(typeof(SpectrumIDFormatType), xmlTypeNsOverride); xmlOverrides.Add(typeof(SourceFileType), xmlTypeNsOverride); xmlOverrides.Add(typeof(SearchDatabaseType), xmlTypeNsOverride); xmlOverrides.Add(typeof(ProteinDetectionProtocolType), xmlTypeNsOverride); xmlOverrides.Add(typeof(TranslationTableType), xmlTypeNsOverride); xmlOverrides.Add(typeof(MassTableType), xmlTypeNsOverride); xmlOverrides.Add(typeof(ResidueType), xmlTypeNsOverride); xmlOverrides.Add(typeof(AmbiguousResidueType), xmlTypeNsOverride); xmlOverrides.Add(typeof(EnzymeType), xmlTypeNsOverride); xmlOverrides.Add(typeof(SpectrumIdentificationProtocolType), xmlTypeNsOverride); xmlOverrides.Add(typeof(SpecificityRulesType), xmlTypeNsOverride); xmlOverrides.Add(typeof(SearchModificationType), xmlTypeNsOverride); xmlOverrides.Add(typeof(EnzymesType), xmlTypeNsOverride); xmlOverrides.Add(typeof(FilterType), xmlTypeNsOverride); xmlOverrides.Add(typeof(DatabaseTranslationType), xmlTypeNsOverride); xmlOverrides.Add(typeof(ProtocolApplicationType), xmlTypeNsOverride); xmlOverrides.Add(typeof(ProteinDetectionType), xmlTypeNsOverride); xmlOverrides.Add(typeof(InputSpectrumIdentificationsType), xmlTypeNsOverride); xmlOverrides.Add(typeof(SpectrumIdentificationType), xmlTypeNsOverride); xmlOverrides.Add(typeof(InputSpectraType), xmlTypeNsOverride); xmlOverrides.Add(typeof(SearchDatabaseRefType), xmlTypeNsOverride); xmlOverrides.Add(typeof(PeptideEvidenceType), xmlTypeNsOverride); xmlOverrides.Add(typeof(PeptideType), xmlTypeNsOverride); xmlOverrides.Add(typeof(ModificationType), xmlTypeNsOverride); xmlOverrides.Add(typeof(SubstitutionModificationType), xmlTypeNsOverride); xmlOverrides.Add(typeof(DBSequenceType), xmlTypeNsOverride); xmlOverrides.Add(typeof(SampleType), xmlTypeNsOverride); xmlOverrides.Add(typeof(ContactRoleType), xmlTypeNsOverride); xmlOverrides.Add(typeof(RoleType), xmlTypeNsOverride); xmlOverrides.Add(typeof(SubSampleType), xmlTypeNsOverride); xmlOverrides.Add(typeof(AbstractContactType), xmlTypeNsOverride); xmlOverrides.Add(typeof(OrganizationType), xmlTypeNsOverride); xmlOverrides.Add(typeof(ParentOrganizationType), xmlTypeNsOverride); xmlOverrides.Add(typeof(PersonType), xmlTypeNsOverride); xmlOverrides.Add(typeof(AffiliationType), xmlTypeNsOverride); xmlOverrides.Add(typeof(ProviderType), xmlTypeNsOverride); xmlOverrides.Add(typeof(AnalysisSoftwareType), xmlTypeNsOverride); xmlOverrides.Add(typeof(InputsType), xmlTypeNsOverride); xmlOverrides.Add(typeof(DataCollectionType), xmlTypeNsOverride); xmlOverrides.Add(typeof(AnalysisProtocolCollectionType), xmlTypeNsOverride); xmlOverrides.Add(typeof(AnalysisCollectionType), xmlTypeNsOverride); xmlOverrides.Add(typeof(SequenceCollectionType), xmlTypeNsOverride); return(xmlOverrides); }
private object ReadArrayContent(object array, ArrayMapping mapping, MemberMapping member, int nestingLevel) { IList list = (IList)array; if (this.m_reader.IsEmptyElement) { this.m_reader.Skip(); } else { this.m_reader.ReadStartElement(); this.m_reader.MoveToContent(); while (this.m_reader.NodeType != XmlNodeType.EndElement && this.m_reader.NodeType != 0) { if (this.m_reader.NodeType == XmlNodeType.Element) { string localName = this.m_reader.LocalName; string namespaceURI = this.m_reader.NamespaceURI; Type type = null; bool flag = false; if (member != null && member.XmlAttributes.XmlArrayItems.Count > nestingLevel) { if (localName == member.XmlAttributes.XmlArrayItems[nestingLevel].ElementName) { XmlArrayItemAttribute xmlArrayItemAttribute = member.XmlAttributes.XmlArrayItems[nestingLevel]; type = xmlArrayItemAttribute.Type; flag = xmlArrayItemAttribute.IsNullable; } } else { XmlElementAttributes xmlElementAttributes = null; if (base.XmlOverrides != null) { XmlAttributes xmlAttributes = base.XmlOverrides[mapping.ItemType]; if (xmlAttributes != null && xmlAttributes.XmlElements != null) { xmlElementAttributes = xmlAttributes.XmlElements; } } if (xmlElementAttributes == null) { mapping.ElementTypes.TryGetValue(localName, out type); } else { foreach (XmlElementAttribute item in xmlElementAttributes) { if (localName == item.ElementName) { type = item.Type; break; } } } } if (type != null) { object value; if (flag && this.m_reader.GetAttribute("nil", "http://www.w3.org/2001/XMLSchema-instance") == "true") { this.m_reader.Skip(); value = null; } else { value = this.ReadObject(type, member, nestingLevel + 1); } list.Add(value); } else { this.m_reader.Skip(); } } else { this.m_reader.Skip(); } this.m_reader.MoveToContent(); } this.m_reader.ReadEndElement(); } return(array); }
/// <summary> /// Serializes the specified Class to XML. /// </summary> /// <param name="path">The path.</param> /// <param name="object">The @object.</param> /// <returns></returns> public static Boolean Serialize(String path, object @object) { try { File.Delete(path); } catch { } FileStream fs = null; try { using (fs = new FileStream(path, FileMode.Create)) { using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8)) { if (@object.GetType().ToString() == "Quester.Profile.QuesterProfile") { // create a XmlAttributes class with empty namespace and namespace disabled var xmlAttributes = new XmlAttributes { XmlType = new XmlTypeAttribute { Namespace = "" }, Xmlns = false }; // create a XmlAttributeOverrides class var xmlAttributeOverrides = new XmlAttributeOverrides(); // implement our previously created XmlAttributes to the overrider for our specificed class xmlAttributeOverrides.Add(@object.GetType(), xmlAttributes); // initialize the serializer for our class and attribute override var s = new System.Xml.Serialization.XmlSerializer(@object.GetType(), xmlAttributeOverrides); // create a blank XmlSerializerNamespaces var xmlSrzNamespace = new XmlSerializerNamespaces(); xmlSrzNamespace.Add("", ""); // Serialize with blank XmlSerializerNames using our initialized serializer with namespace disabled s.Serialize(w, @object, xmlSrzNamespace); // All kind of namespace are totally unable to serialize. } else { var s = new System.Xml.Serialization.XmlSerializer(@object.GetType()); s.Serialize(w, @object); } } } return(true); } catch (Exception ex) { try { if (fs != null) { fs.Close(); } } catch { } Logging.WriteError("Serialize(String path, object @object)#2: " + ex); MessageBox.Show("XML Serialize: " + ex); } return(false); }
private static void ImportPropertyInfo(StructMapping mapping, PropertyInfo prop) { Type type = prop.PropertyType; bool flag = false; if (type.IsGenericType) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable <>)) { flag = true; type = type.GetGenericArguments()[0]; } } bool flag2 = false; XmlAttributes xmlAttributes = new XmlAttributes(); object[] customAttributes = type.GetCustomAttributes(true); object[] customAttributes2 = prop.GetCustomAttributes(true); bool flag3 = false; int num = customAttributes.Length; Array.Resize(ref customAttributes, num + customAttributes2.Length); customAttributes2.CopyTo(customAttributes, num); object[] array = customAttributes; foreach (object obj in array) { Type type2 = obj.GetType(); if (type2 == typeof(XmlIgnoreAttribute)) { return; } if (typeof(DefaultValueAttribute).IsAssignableFrom(type2)) { xmlAttributes.XmlDefaultValue = ((DefaultValueAttribute)obj).Value; } else if (typeof(XmlElementAttribute).IsAssignableFrom(type2)) { XmlElementAttribute xmlElementAttribute = (XmlElementAttribute)obj; xmlAttributes.XmlElements.Add(xmlElementAttribute); if (xmlElementAttribute.Type != null) { if (string.IsNullOrEmpty(xmlElementAttribute.ElementName)) { type = xmlElementAttribute.Type; } else { flag2 = true; } } } else if (type2 == typeof(XmlArrayItemAttribute)) { XmlArrayItemAttribute xmlArrayItemAttribute = (XmlArrayItemAttribute)obj; int j; for (j = 0; j < xmlAttributes.XmlArrayItems.Count && xmlAttributes.XmlArrayItems[j].NestingLevel <= xmlArrayItemAttribute.NestingLevel; j++) { } xmlAttributes.XmlArrayItems.Insert(j, xmlArrayItemAttribute); } else if (typeof(XmlAttributeAttribute).IsAssignableFrom(type2)) { xmlAttributes.XmlAttribute = (XmlAttributeAttribute)obj; } else if (type2 == typeof(ValidValuesAttribute) || type2 == typeof(ValidEnumValuesAttribute)) { flag3 = true; } } string name = prop.Name; string empty = string.Empty; if (!flag2) { TypeMapper.GetMemberName(xmlAttributes, ref name, ref empty); } if (mapping.GetElement(name, empty) == null && mapping.GetAttribute(name, empty) == null) { PropertyMapping propertyMapping = new PropertyMapping(type, name, empty, prop); propertyMapping.XmlAttributes = xmlAttributes; mapping.Members.Add(propertyMapping); if (xmlAttributes.XmlAttribute != null) { if (xmlAttributes.XmlAttribute is XmlChildAttributeAttribute) { mapping.AddChildAttribute(propertyMapping); } else { mapping.Attributes[name, empty] = propertyMapping; } } else { mapping.Elements[name, empty] = propertyMapping; if (flag2) { mapping.AddUseTypeInfo(name, empty); } } Type declaringType = prop.DeclaringType; if (declaringType.IsSubclassOf(typeof(ReportObject))) { Type type3 = declaringType.Assembly.GetType(declaringType.FullName + "+Definition+Properties", false); FieldInfo field; if (type3 != null && type3.IsEnum && (field = type3.GetField(prop.Name)) != null) { propertyMapping.Index = (int)field.GetRawConstantValue(); propertyMapping.TypeCode = PropertyMapping.PropertyTypeCode.Object; if (flag) { propertyMapping.TypeCode = PropertyMapping.PropertyTypeCode.Object; } else if (type.IsSubclassOf(typeof(IContainedObject))) { propertyMapping.TypeCode = PropertyMapping.PropertyTypeCode.ContainedObject; } else if (type == typeof(bool)) { propertyMapping.TypeCode = PropertyMapping.PropertyTypeCode.Boolean; } else if (type == typeof(int)) { propertyMapping.TypeCode = PropertyMapping.PropertyTypeCode.Integer; } else if (type == typeof(ReportSize)) { propertyMapping.TypeCode = PropertyMapping.PropertyTypeCode.Size; } else if (type.IsEnum) { propertyMapping.TypeCode = PropertyMapping.PropertyTypeCode.Enum; } else if (type.IsValueType) { propertyMapping.TypeCode = PropertyMapping.PropertyTypeCode.ValueType; } if (flag3) { type3 = declaringType.Assembly.GetType(declaringType.FullName + "+Definition", false); propertyMapping.Definition = (IPropertyDefinition)type3.InvokeMember("GetProperty", BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.InvokeMethod, null, null, new object[1] { propertyMapping.Index }, CultureInfo.InvariantCulture); } } } } }
/// <summary> /// Saves a new node with the specified attributes. /// </summary> /// <param name="Key">The key.</param> /// <param name="XmlNode">The parent node.</param> /// <param name="Attributes">The attributes.</param> /// <returns></returns> public XmlNode SaveNode(string Key, string XmlNode, XmlAttributes Attributes) { CheckXMLFile(); XmlElement node = (XmlElement)(xmlDocument.DocumentElement.SelectSingleNode((("/" + rootNode + "/") + XmlNode + "/add[@key=\"") + Key + "\"]")); if (node != null) { foreach (string strKey in Attributes.Keys) { node.SetAttribute(strKey, Attributes[strKey]); } return node; } else { node = xmlDocument.CreateElement("add"); node.SetAttribute("key", Key); foreach (string strKey in Attributes.Keys) { node.SetAttribute(strKey.Replace(" ", ""), Attributes[strKey]); } XmlNode Root = xmlDocument.DocumentElement.SelectSingleNode(("/" + rootNode + "/") + XmlNode); if (Root != null) { Root.AppendChild(node); return node; } else { try { Root = xmlDocument.DocumentElement.SelectSingleNode("/" + rootNode + ""); Root.AppendChild(xmlDocument.CreateElement(XmlNode)); Root = xmlDocument.DocumentElement.SelectSingleNode(("/" + rootNode + "/") + XmlNode); Root.AppendChild(node); return node; } catch (Exception ex) { throw new Exception("An error occured while saving the value", ex); } } } }
private void WriteOverriddenAttributes(string filename) { // Writing the file requires a TextWriter. TextWriter myStreamWriter = new StreamWriter(filename); // Create an XMLAttributeOverrides class. XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides(); // Create the XmlAttributes class. XmlAttributes attrs = new XmlAttributes(); /* Override the Student class. "Alumni" is the name * of the overriding element in the XML output. */ XmlElementAttribute attr = new XmlElementAttribute("Alumni", typeof(Graduate)); /* Add the XmlElementAttribute to the collection of * elements in the XmlAttributes object. */ attrs.XmlElements.Add(attr); /* Add the XmlAttributes to the XmlAttributeOverrides. * "Students" is the name being overridden. */ attrOverrides.Add(typeof(HighSchool.MyClass), "Students", attrs); // Create array of extra types. Type [] extraTypes = new Type[2]; extraTypes[0] = typeof(Address); extraTypes[1] = typeof(Phone); // Create an XmlRootAttribute. XmlRootAttribute root = new XmlRootAttribute("Graduates"); /* Create the XmlSerializer with the * XmlAttributeOverrides object. */ XmlSerializer mySerializer = new XmlSerializer (typeof(HighSchool.MyClass), attrOverrides, extraTypes, root, "http://www.microsoft.com"); MyClass myClass = new MyClass(); Graduate g1 = new Graduate(); g1.Name = "Jacki"; g1.ID = 1; g1.University = "Alma"; Graduate g2 = new Graduate(); g2.Name = "Megan"; g2.ID = 2; g2.University = "CM"; Student[] myArray = { g1, g2 }; myClass.Students = myArray; // Create extra information. Address a1 = new Address(); a1.City = "Ionia"; Address a2 = new Address(); a2.City = "Stamford"; Phone p1 = new Phone(); p1.Number = "555-0101"; Phone p2 = new Phone(); p2.Number = "555-0100"; Object[] o1 = new Object[2] { a1, p1 }; Object[] o2 = new Object[2] { a2, p2 }; g1.Info = o1; g2.Info = o2; mySerializer.Serialize(myStreamWriter, myClass); myStreamWriter.Close(); }
public override string ToString () { string result = string.Empty; using (MemoryStream stream = new MemoryStream ()) { using (StreamReader sr = new StreamReader (stream)) { XmlTextWriter writer = null; try { writer = new XmlTextWriter (stream, System.Text.Encoding.UTF8); XmlAttributes attrs = new XmlAttributes (); XmlElementAttribute attr = new XmlElementAttribute (); attr.ElementName = "UnknownItemSerializer"; attr.Type = typeof (UnknownItemSerializer); attrs.XmlElements.Add (attr); XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides (); attrOverrides.Add (typeof (TestClass), "Item", attrs); XmlSerializer serializer = new XmlSerializer (this.GetType (), attrOverrides); serializer.Serialize (writer, this); stream.Position = 0; result = sr.ReadToEnd (); } finally { if (writer != null) writer.Close (); } } } return result; }
public void Add (Type type, string member, XmlAttributes attributes) { throw new NotImplementedException (); }
public void SerializeObject(string studentFilename, string bookFilename) { XmlSerializer mySerializer; TextWriter writer; // Create the XmlAttributeOverrides and XmlAttributes objects. XmlAttributeOverrides myXmlAttributeOverrides = new XmlAttributeOverrides(); XmlAttributes myXmlAttributes = new XmlAttributes(); /* Create an XmlAttributeAttribute set it to * the XmlAttribute property of the XmlAttributes object.*/ XmlAttributeAttribute myXmlAttributeAttribute = new XmlAttributeAttribute(); myXmlAttributeAttribute.AttributeName = "Name"; myXmlAttributes.XmlAttribute = myXmlAttributeAttribute; // Add to the XmlAttributeOverrides. Specify the member name. myXmlAttributeOverrides.Add(typeof(Student), "StudentName", myXmlAttributes); // Create the XmlSerializer. mySerializer = new XmlSerializer(typeof(Student), myXmlAttributeOverrides); writer = new StreamWriter(studentFilename); // Create an instance of the class that will be serialized. Student myStudent = new Student(); // Set the Name property, which will be generated as an XML attribute. myStudent.StudentName = "James"; myStudent.StudentNumber = 1; // Serialize the class, and close the TextWriter. mySerializer.Serialize(writer, myStudent); writer.Close(); // Create the XmlAttributeOverrides and XmlAttributes objects. XmlAttributeOverrides myXmlBookAttributeOverrides = new XmlAttributeOverrides(); XmlAttributes myXmlBookAttributes = new XmlAttributes(); /* Create an XmlAttributeAttribute set it to * the XmlAttribute property of the XmlAttributes object.*/ XmlAttributeAttribute myXmlBookAttributeAttribute = new XmlAttributeAttribute("Name"); myXmlBookAttributes.XmlAttribute = myXmlBookAttributeAttribute; // Add to the XmlAttributeOverrides. Specify the member name. myXmlBookAttributeOverrides.Add(typeof(Book), "BookName", myXmlBookAttributes); // Create the XmlSerializer. mySerializer = new XmlSerializer(typeof(Book), myXmlBookAttributeOverrides); writer = new StreamWriter(bookFilename); // Create an instance of the class that will be serialized. Book myBook = new Book(); // Set the Name property, which will be generated as an XML attribute. myBook.BookName = ".NET"; myBook.BookNumber = 10; // Serialize the class, and close the TextWriter. mySerializer.Serialize(writer, myBook); writer.Close(); }