public XmlSerializer CreateOverrider() { // Create an XmlSerializer with overriding attributes. XmlAttributeOverrides xOver = new XmlAttributeOverrides(); /* Create an XmlAttributeAttribute object and set the * AttributeName property. */ XmlAttributeAttribute xAtt = new XmlAttributeAttribute(); xAtt.AttributeName = "Code"; /* Create a new XmlAttributes object and set the * XmlAttributeAttribute object to the XmlAttribute property. */ XmlAttributes attrs = new XmlAttributes(); attrs.XmlAttribute = xAtt; /* Add the XmlAttributes to the XmlAttributeOverrides object. The * name of the overridden attribute must be specified. */ xOver.Add(typeof(Group), "GroupCode", attrs); // Get the XmlAttributes object for the type and member. XmlAttributes tempAttrs; tempAttrs = xOver[typeof(Group), "GroupCode"]; Console.WriteLine(tempAttrs.XmlAttribute.AttributeName); // Create the XmlSerializer instance and return it. XmlSerializer xSer = new XmlSerializer(typeof(Group), xOver); return(xSer); }
private static GeneratedSegment ParseXml(TextRange range) { try { var tag = new GeneratedSegment(range); var xmlProps = XmlAttributeAttribute.GetXmlProperties(typeof(GeneratedSegment)); var xTag = ExtractXml(range); foreach (var attr in xTag.Attributes()) { var name = attr.Name.LocalName; //skip renderer name if (name == XmlRendererAttributeName) { continue; } var prop = xmlProps[name]; prop.SetValue(tag, ParseXmlAttributeValue(prop, attr.Value)); } return(tag); } catch (Exception ex) { Debug.DebugHere(ex); throw; } }
private static void PopulateSegmentWithXml(GeneratedSegment tag, XElement xTag) { try { var xmlProps = XmlAttributeAttribute.GetXmlProperties(typeof(GeneratedSegment)); foreach (var attr in xTag.Attributes()) { var name = attr.Name.LocalName; //skip renderer name if (name == TemplateNamePropertyName) { continue; } var prop = xmlProps[name]; var value = XmlAttributeAttribute.ParsePropertyValue(prop, attr.Value); prop.SetValue(tag, value); } } catch (Exception ex) { Debug.DebugHere(ex); throw; } }
/// <summary> /// Initializes the XML attribute attribute. /// </summary> /// <param name="type">The type.</param> /// <param name="attribute">The attribute. Can be <c>null</c> if not decorated with an attribute.</param> /// <param name="propertyName">Name of the property.</param> /// <returns><c>true</c> if the attribute is handled by this mapper; otherwise, <c>false</c>.</returns> /// <exception cref="ArgumentNullException">The <paramref name="type"/> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">The <paramref name="propertyName"/> is <c>null</c> or whitespace.</exception> private bool InitializeXmlAttributeAttribute(Type type, XmlAttributeAttribute attribute, string propertyName) { Argument.IsNotNull("type", type); Argument.IsNotNullOrWhitespace("propertyName", propertyName); if (typeof(T) != typeof(XmlAttributeAttribute)) { // If attribute has a value, we simply do not support it, but we return true because // it should be seen as handled return(attribute != null); } if (attribute != null) { string mappedName = attribute.AttributeName; if (string.IsNullOrWhiteSpace(mappedName)) { mappedName = propertyName; } _xmlNameToPropertyNameMappings[type].Add(mappedName, propertyName); _xmlPropertyNameToXmlNameMappings[type].Add(propertyName, mappedName); } return(true); }
public void Ex2_AttribReshape() { string path = @"..\..\..\TmpFile"; string file = Path.Combine(path, @"ClassRoom.xml"); XmlAttributes attrs = new XmlAttributes(); // Create an XmlElementAttribute to override the Instrument. XmlAttributeAttribute attr = new XmlAttributeAttribute(); attr.AttributeName = "Brass"; // Add the XmlElementAttribute to the collection of objects. attrs.XmlAttribute = attr; XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides(); attrOverrides.Add(typeof(ClassRoom), "RoomNumber", attrs); // Writing the file requires a TextWriter. using (TextWriter writer = new StreamWriter(file)) { // Create the XmlSerializer using the XmlAttributeOverrides. XmlSerializer s = new XmlSerializer(typeof(ClassRoom), attrOverrides); // Create the object that will be serialized. ClassRoom band = new ClassRoom() { RoomNumber = "1931" }; // Serialize the object. s.Serialize(writer, band); } }
public XElement GenXmlTag() { //set to null if it's default, so it doesn't need to be written in the tag var isTriggeredByBaseClass = TriggeringBaseClass != null && TriggeringBaseClass != Class; var triggerType = isTriggeredByBaseClass ? (TriggerTypes?)TriggerTypes.AttributeInBaseClass : null; var triggerInfo = (triggerType == TriggerTypes.AttributeInBaseClass) ? TriggeringBaseClass.Name : null; var xml = new XElement(Tag.TagPrototype); if (triggerType != null) { xml.SetAttributeValue("Trigger", triggerType.ToString()); } if (triggerInfo != null) { xml.SetAttributeValue("TriggerInfo", triggerInfo); } xml.SetAttributeValue(Tag.GenerateDatePropertyName, DateTime.Now.ToString(Constants.TagDateFormat, Constants.TagDateCulture)); foreach (var keyValuePair in XmlAttributeAttribute.GetXmlProperties(typeof(Tag))) { var propValue = keyValuePair.Value.GetValue(OptionTag); //only write the xml attribute if it has a value, to keep the tag concise if (propValue != null) { xml.Add(new XAttribute(keyValuePair.Key, propValue)); } } return(xml); }
private void button2_Click(object sender, EventArgs e) { string xml = string.Empty; RenderParameterBase p = new RenderParameter();//new RenderParameterBase(); p.Name = "name1"; p.Value = new Object[] { true, false }; p.sappid = 1; if (p != null) { using (MemoryStream stream = new MemoryStream()) { using (XmlWriter writer = XmlWriter.Create(stream, new XmlWriterSettings { Encoding = UTF8Encoding })) { XmlSerializer serializer = new XmlSerializer(typeof(RenderParameter)); XmlAttributeAttribute att1 = new XmlAttributeAttribute(); att1.AttributeName = "ss"; serializer.Serialize(writer, p); } xml = UTF8Encoding.GetString(stream.ToArray()); } } textBox1.Text = xml; }
public override void WriteXml(System.Xml.XmlWriter writer) { XmlRootAttribute root = (XmlRootAttribute)this.GetType().GetCustomAttributes(typeof(XmlRootAttribute), true).First <object>(); PropertyInfo[] properties = this.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); foreach (PropertyInfo property in properties) { if (property.GetCustomAttributes(typeof(XmlAttributeAttribute), true).Length == 1) { string value = null; if (property.Name == "Status") { value = ((int)this.Status).ToString(); } else { value = property.GetValue(this, null) as String; } if (!String.IsNullOrEmpty(value)) { XmlAttributeAttribute attribute = (XmlAttributeAttribute)property.GetCustomAttributes(typeof(XmlAttributeAttribute), true).First <object>(); writer.WriteAttributeString(attribute.AttributeName, value); } } } }
protected override Serializer <FilteringContext> CreateAttributeSerializer(PropertyInfo property, XmlAttributeAttribute attributeAttribute) { var serializer = base.CreateAttributeSerializer(property, attributeAttribute); if (attributeAttribute.OmitIfNull) { var name = attributeAttribute.Name; var @namespace = attributeAttribute.Namespace; return((obj, context) => { string prefix; if (string.IsNullOrEmpty(@namespace)) { prefix = null; } else { prefix = context.Writer.LookupPrefix(@namespace); } var id = PropertyName.CreateForAttribute(name, prefix, context.Context.NestedPropertyName); if (context.Context.IncludesAttribute(id)) { serializer(obj, context); } }); } else { return(serializer); } }
/// <summary/> protected override List <PropertyDescriptor> SortAttributedProperties(object obj) { //Gets all the properties for an object and sorts them by //which properties want to be serialized as an XMLAttribute //This is required since attribute must be serialized before elements List <PropertyDescriptor> props = new List <PropertyDescriptor>(); List <PropertyDescriptor> elementProps = new List <PropertyDescriptor>(); PropertyDescriptorCollection oldProps = TypeDescriptor.GetProperties(obj); XmlAttributeAttribute xmlAttr = new XmlAttributeAttribute(); //Creating this allows us to avoid calling the contructor for every iteration foreach (PropertyDescriptor prop in oldProps) { if (prop.Attributes.Contains(xmlAttr)) //Add the PropertyDescriptors that contain XmlAttributes { props.Add(prop); } else { elementProps.Add(prop); } } props.AddRange(elementProps); //Add the element based properties return(props); }
public override void WriteXml(System.Xml.XmlWriter writer) { XmlRootAttribute root = (XmlRootAttribute)this.GetType().GetCustomAttributes(typeof(XmlRootAttribute), true).First <object>(); PropertyInfo[] properties = this.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); PropertyInfo property = properties.First <PropertyInfo>(delegate(PropertyInfo prop){ return(prop.Name == "BaseUri"); }); XmlAttributeAttribute attribute = (XmlAttributeAttribute)property.GetCustomAttributes(typeof(XmlAttributeAttribute), true).Single <object>(); writer.WriteAttributeString(attribute.AttributeName, WADLUtility.Url.CreateUrl(this.BaseUri.OriginalString, relativeUri)); foreach (WADLMethod method in Methods) { using (MemoryStream mem = new MemoryStream()) { XmlSerializer rez = new XmlSerializer(typeof(WADLMethod), root.Namespace); rez.Serialize(mem, method); mem.Flush(); mem.Position = 0; using (StreamReader sr = new StreamReader(mem)) { sr.ReadLine(); writer.WriteRaw(sr.ReadToEnd()); sr.Close(); } mem.Close(); } } }
public XmlSerializer CreateOverrider() { // Create an XmlAttributeOverrides object. XmlAttributeOverrides xOver = new XmlAttributeOverrides(); /* Create an XmlAttributeAttribute to override the base class * object's XmlAttributeAttribute object. Give the overriding object * a new attribute name ("Code"). */ XmlAttributeAttribute xAtt = new XmlAttributeAttribute(); xAtt.AttributeName = "Code"; /* Create an instance of the XmlAttributes class and set the * XmlAttribute property to the XmlAttributeAttribute object. */ XmlAttributes attrs = new XmlAttributes(); attrs.XmlAttribute = xAtt; /* Add the XmlAttributes object to the XmlAttributeOverrides * and specify the type and member name to override. */ xOver.Add(typeof(Group), "GroupCode", attrs); XmlSerializer xSer = new XmlSerializer(typeof(Group), xOver); return(xSer); }
/// <summary> /// Asserts whether the property <paramref name="propertyName"/> in class <typeparamref name="T"/> /// has a <see cref="XmlElementAttribute"/> with the correct values. /// </summary> /// <typeparam name="T">The class the <paramref name="propertyName"/> is in.</typeparam> /// <param name="propertyName">The name of the property to assert.</param> /// <param name="elementName">The expected XML element name.</param> /// <param name="namespaceUrl">The expected XML namespace url.</param> /// <exception cref="AssertionException">Thrown when: /// <list type="bullet"> /// <item>the <see cref="XmlElementAttribute"/> could not be found;</item> /// <item>multiple attributes of type <see cref="XmlAttributeAttribute"/> were found;</item> /// <item>the actual attribute does not match with the given <paramref name="elementName"/> /// and <paramref name="namespaceUrl"/>.</item> /// </list> /// </exception> public static void AssertXmlAttributeAttribute <T>(string propertyName, string elementName, string namespaceUrl = null) where T : class { XmlAttributeAttribute attribute = GetPropertyAttribute <T, XmlAttributeAttribute>(propertyName); Assert.AreEqual(elementName, attribute.AttributeName); Assert.AreEqual(namespaceUrl, attribute.Namespace); }
public void DataTypeDefault() { XmlAttributeAttribute attr = new XmlAttributeAttribute(); Assert.AreEqual(string.Empty, attr.DataType, "#1"); attr.DataType = null; Assert.AreEqual(string.Empty, attr.DataType, "#2"); }
protected override Serializer <VirtualContext> CreateAttributeSerializer(PropertyInfo property, XmlAttributeAttribute attributeAttribute) { var name = string.IsNullOrEmpty(attributeAttribute.Name) ? property.Name : attributeAttribute.Name; var @namespace = attributeAttribute.Namespace; var serializer = base.CreateAttributeSerializer(property, attributeAttribute); return(CreateSerializer(name, @namespace, serializer)); }
public void AttributeNameDefault() { XmlAttributeAttribute attr = new XmlAttributeAttribute(); Assert.AreEqual(string.Empty, attr.AttributeName, "#1"); attr.AttributeName = null; Assert.AreEqual(string.Empty, attr.AttributeName, "#2"); }
private void ReadChildAttribute(object obj, StructMapping mapping, MemberMapping childMapping) { XmlAttributeAttribute xmlAttribute = childMapping.XmlAttributes.XmlAttribute; string attribute = this.m_reader.GetAttribute(xmlAttribute.AttributeName, xmlAttribute.Namespace); if (attribute != null) { childMapping.SetValue(obj, attribute); } }
//attributes have to be simple types, either enum, string, int, double, bool private static void AddXMLAttributte(FileLevelInfo info, XmlAttributeAttribute xa, ClassSnippet snip, FieldInfo finfo) { string fieldName = xa.AttributeName; string dtype = SetupSimpleType(info, snip, xa.DataType, fieldName, finfo.FieldType.Name); snip.fromXml += "\t" + fieldName + " = FromString_" + dtype + "(pEm, pEm->Attribute(\"" + fieldName + "\"));\n"; snip.toXml += "\tpEm->SetAttribute(\"" + fieldName + "\", ToString_" + dtype + "(" + fieldName + "));\n"; snip.declarations += "\t" + dtype + " " + fieldName + ";\n"; }
protected virtual Serializer <TContext> CreateAttributeSerializer(PropertyInfo property, XmlAttributeAttribute attributeAttribute) { return(CreateSerializer( CreateAttributeSerializer( property, string.IsNullOrEmpty(attributeAttribute.Name) ? property.Name : attributeAttribute.Name, attributeAttribute.Namespace, attributeAttribute.Prefix), attributeAttribute.OmitIfNull)); }
/// <summary> /// Serializes a value into an XML attribute /// </summary> /// <param name="property"></param> /// <param name="value"></param> /// <param name="attributeAttr"></param> /// <returns></returns> private XAttribute SerializeAttribute(PropertyInfo property, object value, XmlAttributeAttribute attributeAttr) { // Attribute name can be set via the attribute, else it'll use the property name var attributeName = !string.IsNullOrEmpty(attributeAttr.AttributeName) ? attributeAttr.AttributeName : property.Name; // namespace defaults to blank unless it's specified in the attribute var ns = attributeAttr.Namespace ?? XNamespace.None; return(new XAttribute(ns + attributeName, value)); }
protected void IgnorarElemento(string nomeElemento, bool condicao) { var attr = new XmlAttributes(); //attr.XmlIgnore = condicao; var a = new XmlAttributeAttribute("Teste"); attr.XmlAttribute = a; this._xmlAttributeOverrides.Add(typeof(T), nomeElemento, attr); }
private void WriteChildAttribute(XmlWriter writer, object obj, MemberMapping mapping) { if (obj != null) { XmlAttributeAttribute xmlAttribute = mapping.XmlAttributes.XmlAttribute; string value = obj.ToString(); if (!string.IsNullOrEmpty(value)) { writer.WriteAttributeString(xmlAttribute.AttributeName, xmlAttribute.Namespace, value); } } }
public LiteralAttributes(MemberInfo memberInfo, XmlAttributes xmlAtts) : this(memberInfo) { if (xmlAtts == null) { return; } Ignore = xmlAtts.XmlIgnore; if (!Ignore) { XmlChoiceIdentifier = xmlAtts.XmlChoiceIdentifier; XmlAttribute = xmlAtts.XmlAttribute; XmlArray = xmlAtts.XmlArray; XmlText = xmlAtts.XmlText; XmlEnum = xmlAtts.XmlEnum; DefaultValue = (xmlAtts.XmlDefaultValue == null) ? null : new DefaultValueAttribute(xmlAtts.XmlDefaultValue); Xmlns = xmlAtts.Xmlns; if (Xmlns) { object[] attrs = memberInfo.GetCustomAttributes(s_nsDeclType, false).ToArray(); XmlNamespaceDeclaration = (XmlNamespaceDeclarationsAttribute)(attrs.Length > 0 ? attrs[0] : null); } else { XmlNamespaceDeclaration = null; } // Use if statements here so that the XmlElements collection populated by reflection // is eliminated only if the app developer has provided substitute XmlElementAttribute's. // Ditto for the XmlArrayItems and XmlAnyElements. if (xmlAtts.XmlElements.Count > 0) { XmlElements = xmlAtts.XmlElements; } if (xmlAtts.XmlArrayItems.Count > 0) { XmlArrayItems = xmlAtts.XmlArrayItems; } XmlAnyAttribute = xmlAtts.XmlAnyAttribute; if (xmlAtts.XmlAnyElements.Count > 0) { XmlAnyElements = xmlAtts.XmlAnyElements; } } }
public XElement Convert(object entity) { XElement element = new XElement(entity.GetType().Name); List <PropertyInfo> attributePropertyInfos = entity.GetType().GetProperties().Where(x => Attribute.IsDefined(x, typeof(XmlAttributeAttribute))).ToList(); foreach (PropertyInfo attributePropertyInfo in attributePropertyInfos) { XmlAttributeAttribute xmlAttribute = attributePropertyInfo.GetCustomAttribute <XmlAttributeAttribute>(); element.Add(new XAttribute(xmlAttribute.AttributeName, attributePropertyInfo.GetValue(entity))); } return(element); }
public void XmlArrayDifferentNames() { XmlAttributeAttribute attribute1 = new XmlAttributeAttribute("myname"); XmlAttributeAttribute attribute2 = new XmlAttributeAttribute("myothername"); atts1.XmlAttribute = attribute1; atts2.XmlAttribute = attribute2; ov1.Add(typeof(SerializeMe), atts1); ov2.Add(typeof(SerializeMe), atts2); ThumbprintHelpers.DifferentThumbprint(ov1, ov2); }
public void XmlArraySameName() { XmlAttributeAttribute attribute1 = new XmlAttributeAttribute("myname"); XmlAttributeAttribute attribute2 = new XmlAttributeAttribute("myname"); atts1.XmlAttribute = attribute1; atts2.XmlAttribute = attribute2; ov1.Add(typeof(SerializeMe), atts1); ov2.Add(typeof(SerializeMe), atts2); ThumbprintHelpers.SameThumbprint(ov1, ov2); }
public void DifferentMemberName() { XmlAttributeAttribute attribute1 = new XmlAttributeAttribute("myname"); XmlAttributeAttribute attribute2 = new XmlAttributeAttribute("myname"); atts1.XmlAttribute = attribute1; atts2.XmlAttribute = attribute2; ov1.Add(typeof(SerializeMe), "TheMember", atts1); ov2.Add(typeof(SerializeMe), "TheOtherMember", atts2); ThumbprintHelpers.DifferentThumbprint(ov1, ov2); }
/// <summary> /// Gets the serialized name for the member. /// </summary> /// <param name="member"></param> /// <returns></returns> public override IEnumerable <DataName> GetName(MemberInfo member) { if (member is Type) { XmlRootAttribute rootAttr = TypeCoercionUtility.GetAttribute <XmlRootAttribute>(member); if (rootAttr != null && !String.IsNullOrEmpty(rootAttr.ElementName)) { yield return(new DataName(rootAttr.ElementName, null, rootAttr.Namespace)); } XmlTypeAttribute typeAttr = TypeCoercionUtility.GetAttribute <XmlTypeAttribute>(member); if (typeAttr != null && !String.IsNullOrEmpty(typeAttr.TypeName)) { yield return(new DataName(typeAttr.TypeName, null, typeAttr.Namespace)); } yield break; } XmlElementAttribute elemAttr = TypeCoercionUtility.GetAttribute <XmlElementAttribute>(member); if (elemAttr != null && !String.IsNullOrEmpty(elemAttr.ElementName)) { yield return(new DataName(elemAttr.ElementName, null, elemAttr.Namespace)); } XmlAttributeAttribute attrAttr = TypeCoercionUtility.GetAttribute <XmlAttributeAttribute>(member); if (attrAttr != null && !String.IsNullOrEmpty(attrAttr.AttributeName)) { yield return(new DataName(attrAttr.AttributeName, null, attrAttr.Namespace, true)); } XmlArrayAttribute arrayAttr = TypeCoercionUtility.GetAttribute <XmlArrayAttribute>(member); if (arrayAttr != null && !String.IsNullOrEmpty(arrayAttr.ElementName)) { // TODO: figure out a way to surface XmlArrayItemAttribute name too yield return(new DataName(arrayAttr.ElementName, null, arrayAttr.Namespace)); } if (member is FieldInfo && ((FieldInfo)member).DeclaringType.IsEnum) { XmlEnumAttribute enumAttr = TypeCoercionUtility.GetAttribute <XmlEnumAttribute>(member); if (enumAttr != null && !String.IsNullOrEmpty(enumAttr.Name)) { yield return(new DataName(enumAttr.Name)); } } }
bool ProcessAttributeAttribute(PropertyInfo propertyInfo, XmlAttributeAttribute attribute) { if (attribute != null) { var name = string.IsNullOrEmpty(attribute.Name) ? propertyInfo.Name : attribute.Name; var id = PropertyName.CreateForAttribute(name, attribute.Prefix, null); properties[id] = new ValuePropertyVisitor(attribute.OmitIfNull, propertyInfo); return(true); } else { return(false); } }
public override void WriteXml(System.Xml.XmlWriter writer) { XmlRootAttribute root = (XmlRootAttribute)this.GetType().GetCustomAttributes(typeof(XmlRootAttribute), true).First <object>(); PropertyInfo[] properties = this.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public); foreach (PropertyInfo property in properties) { if (property.GetCustomAttributes(typeof(XmlAttributeAttribute), true).Length == 1) { XmlAttributeAttribute attribute = (XmlAttributeAttribute)property.GetCustomAttributes(typeof(XmlAttributeAttribute), true).First <object>(); writer.WriteAttributeString(attribute.AttributeName, property.GetValue(this, null).ToString()); } } }