internal static bool DecodeXmlTextReaderValue(object instance, System.Reflection.PropertyInfo propertyInfo, System.Xml.XmlReader xmlTextReader) { try { // find related property by name if not provided as parameter if(propertyInfo==null) propertyInfo = instance.GetType().GetProperty(xmlTextReader.Name, System.Reflection.BindingFlags.IgnoreCase | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); // if(propertyInfo==null) return false; // unescaped characters <>& if(propertyInfo.PropertyType.Equals(typeof(string))) { propertyInfo.SetValue(instance, Decode(xmlTextReader.ReadInnerXml().Trim()),null); } else if(propertyInfo.PropertyType.Equals(typeof(DateTime))) { propertyInfo.SetValue(instance, ParseRfc822DateTime(xmlTextReader.ReadInnerXml().Trim()),null); } else { propertyInfo.SetValue(instance, System.ComponentModel.TypeDescriptor.GetConverter(propertyInfo.PropertyType).ConvertFromString(xmlTextReader.ReadInnerXml().Trim()), null); } } catch(System.Exception e) { System.Diagnostics.Debug.WriteLine(propertyInfo.Name +", " + propertyInfo.PropertyType.Name +" / " + instance.ToString() + " " + e.Message); return false; } return true; }
protected override bool OnDeserializeUnrecognizedElement(string elementName, System.Xml.XmlReader reader) { if (OptionElements == null) OptionElements = new NameValueCollection(); //Because ConfigurationElement.DeserializeElemenet() method only accept outerXml and in MS.NET, it accept innerXml, //so there is a hack over here OptionElements.Add(elementName, Platform.IsMono ? reader.ReadOuterXml() : reader.ReadInnerXml()); return true; }
/// <summary>Initializes a new instance of RssCloud</summary> public RssCloud (System.Xml.XmlReader xmlTextReader) { if(!xmlTextReader.HasAttributes) return; // System.Reflection.PropertyInfo propertyInfo = null; // while(xmlTextReader.MoveToNextAttribute()) { // find related property by name propertyInfo = GetType().GetProperty(xmlTextReader.Name, System.Reflection.BindingFlags.IgnoreCase | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); if(propertyInfo!=null) { // Protocol enum needs some conversion before the typeconverter can set the values that contains - char if(propertyInfo.Name == "Protocol") { propertyInfo.SetValue(this, System.ComponentModel.TypeDescriptor.GetConverter(propertyInfo.PropertyType).ConvertFromString(xmlTextReader.ReadInnerXml().Trim().Replace("-","")),null); } else { XmlSerializationUtil.DecodeXmlTextReaderValue(this, xmlTextReader); } } } }
/// <summary>Initializes a new instance of OpmlOutline</summary> public OpmlOutline (System.Xml.XmlReader xmlTextReader): this() { if(!xmlTextReader.HasAttributes) return; // get attributes System.Reflection.PropertyInfo propertyInfo = null; for(int i =0;i<xmlTextReader.AttributeCount;i++) { xmlTextReader.MoveToAttribute(i); // try to find some common used alias names for attributes string attributeName = xmlTextReader.Name; if(attributeName.IndexOf("url")!=-1) attributeName = "xmlUrl"; if(attributeName.IndexOf("title")!=-1) attributeName = "text"; // find related property by name propertyInfo = GetType().GetProperty(attributeName, System.Reflection.BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); if(propertyInfo!=null) { propertyInfo.SetValue(this, System.ComponentModel.TypeDescriptor.GetConverter(propertyInfo.PropertyType).ConvertFromString(xmlTextReader.ReadInnerXml().Trim()),null); } } }
//================================================================================ // Function/Sub: ParseOAIcontainer // Description: Function used to return an entire XML node //================================================================================ private string ParseOAIContainer(ref System.Xml.XmlTextReader reader, string sNode) { while (reader.NodeType != System.Xml.XmlNodeType.EndElement) { if (reader.Name == sNode) { return reader.ReadInnerXml(); } } return ""; }
/// <summary> /// Parse an object from <paramref name="s"/> /// </summary> public object Parse(System.Xml.XmlReader s, DatatypeR2FormatterParseResult result) { // Parse base (ANY) from the stream ANYFormatter baseFormatter = new ANYFormatter(); string pathName = s is XmlStateReader ? (s as XmlStateReader).CurrentPath : s.Name; // Parse ED ED retVal = baseFormatter.Parse<ED>(s); // Now parse our data out... Attributes if (s.GetAttribute("mediaType") != null) retVal.MediaType = s.GetAttribute("mediaType"); if (s.GetAttribute("language") != null) retVal.Language = s.GetAttribute("language"); if (s.GetAttribute("compression") != null) retVal.Compression = (EncapsulatedDataCompression?)Util.FromWireFormat(s.GetAttribute("compression"), typeof(EncapsulatedDataCompression)); if (s.GetAttribute("integrityCheckAlgorithm") != null) retVal.IntegrityCheckAlgorithm = Util.Convert<EncapsulatedDataIntegrityAlgorithm>(s.GetAttribute("integrityCheckAlgorithm")); if (s.GetAttribute("value") != null) { retVal.Representation = EncapsulatedDataRepresentation.TXT; if(retVal.MediaType == null) retVal.MediaType = "text/plain"; retVal.Value = s.GetAttribute("value"); } // Elements and inner data #region Elements if (!s.IsEmptyElement) { // Exit markers int sDepth = s.Depth; string sName = s.Name; Encoding textEncoding = System.Text.Encoding.UTF8; s.Read(); // Read until exit condition is fulfilled while (!(s.NodeType == System.Xml.XmlNodeType.EndElement && s.Depth == sDepth && s.Name == sName)) { string oldName = s.Name; // Name try { if (s.LocalName == "thumbnail") // Format using ED { var hostResult = Host.Parse(s, typeof(ED)); result.Code = hostResult.Code; result.AddResultDetail(hostResult.Details); retVal.Thumbnail = (ED)hostResult.Structure; } else if (s.LocalName == "reference") // Format using TEL { var hostResult = Host.Parse(s, typeof(TEL)); result.Code = hostResult.Code; result.AddResultDetail(hostResult.Details); retVal.Reference = (TEL)hostResult.Structure; } else if (s.LocalName == "translation") // Translation { var hostResult = Host.Parse(s, typeof(ED)); result.Code = hostResult.Code; result.AddResultDetail(hostResult.Details); if (retVal.Translation == null) retVal.Translation = new SET<ED>(); retVal.Translation.Add((ED)hostResult.Structure); } else if (s.LocalName == "data") // Data { retVal.Representation = EncapsulatedDataRepresentation.B64; retVal.Data = Convert.FromBase64String(s.ReadString()); } else if (s.LocalName == "xml") // data { retVal.Representation = EncapsulatedDataRepresentation.XML; retVal.Data = textEncoding.GetBytes(s.ReadInnerXml()); } else if (s.LocalName == "integrityCheck") { retVal.IntegrityCheck = Convert.FromBase64String(s.ReadString()); } } catch (MessageValidationException e) { result.AddResultDetail(new MARC.Everest.Connectors.ResultDetail(MARC.Everest.Connectors.ResultDetailType.Error, e.Message, s.ToString(), e)); } finally { if (s.Name == oldName) s.Read(); } } } #endregion // Finally, the hash, this will validate the data if (!retVal.ValidateIntegrityCheck()) result.AddResultDetail(new ResultDetail(ResultDetailType.Warning, string.Format("Encapsulated data with content starting with '{0}' failed integrity check!", retVal.ToString().PadRight(10, ' ').Substring(0, 10)), s.ToString(), null)); // Validate baseFormatter.Validate(retVal, pathName, result); return retVal; }
/// <summary> /// Generates an object from its XML representation. /// </summary> /// <param name="reader">The <see cref="XmlReader" /> stream from which the object is deserialized.</param> public void ReadXml(System.Xml.XmlReader reader) { int initialDepth = reader.Depth; while (reader.Read() && reader.Depth >= initialDepth) { while (reader.IsStartElement()) { switch (reader.Name) { case IdElementName: this.Id = reader.ReadString(); break; case SequenceNumberElementName: this.SequenceNumber = int.Parse(reader.ReadString()); break; case CommentElementName: this.Comment = reader.ReadString(); break; case PersonElementName: this.Person = Utility.Utilities.DeserializeXml<Person>(string.Format("<person>{0}</person>", reader.ReadInnerXml())); break; case TimestampElementName: this.Timestamp = long.Parse(reader.ReadString()); break; default: reader.Read(); break; } } } }
public void ReadXml(System.Xml.XmlReader reader) { Text = reader.ReadInnerXml(); }
/// <summary> /// Reads the Property from the XML. /// </summary> /// <param name="reader">The instance of the XmlReader.</param> void IXmlSerializable.ReadXml(System.Xml.XmlReader reader) { ReadBasicXmlInfo(reader); if(reader.MoveToAttribute("IsOutput")) this.IsOutput = Convert.ToBoolean(reader.ReadContentAsString()); if (reader.MoveToAttribute("IsMonitored")) this.IsMonitored = Convert.ToBoolean(reader.ReadContentAsString()); if(reader.MoveToAttribute("ConnectedToUID")) this.ConnectedToUID = reader.ReadContentAsString(); if (reader.IsEmptyElement == false) { reader.ReadStartElement(); if (reader.Name == "anyType") { try { XmlSerializer ser = new XmlSerializer(typeof(object)); this.Value = ser.Deserialize(reader); } catch (Exception ex) { Trace.WriteLine(ex.Message, ex.StackTrace, LogCategory.Error); } } else if(reader.Name == "ArrayOfDouble") { try { XmlSerializer ser = new XmlSerializer(typeof(List<double>)); this.Value = ser.Deserialize(reader); } catch (Exception ex) { Trace.WriteLine(ex.Message, ex.StackTrace, LogCategory.Error); } } else if (reader.Name == "ArrayOfInteger") { try { XmlSerializer ser = new XmlSerializer(typeof(List<int>)); this.Value = ser.Deserialize(reader); } catch (Exception ex) { Trace.WriteLine(ex.Message, ex.StackTrace, LogCategory.Error); } } } if (reader.Name == "Cache" && reader.IsStartElement()) { reader.ReadStartElement(); try { XmlSerializer ser = new XmlSerializer(this.Cache.GetType()); this.Cache = ser.Deserialize(reader) as Cache; } catch (Exception ex) { Trace.WriteLine(ex.Message, ex.StackTrace, LogCategory.Error); } this.Childs = new List<object>(this.Cache.Childs); } if(reader.Name.Contains("ToleranceOf") && reader.IsStartElement()) { reader.ReadStartElement(); this.Tolerance = new Tolerance<object>(); string min = reader.ReadInnerXml(); string max = reader.ReadInnerXml(); this.Tolerance.Min = min; this.Tolerance.Max = max; } while (!reader.IsStartElement()) { if (reader.Name == "Cache") { reader.ReadEndElement(); break; } reader.ReadEndElement(); } }
/// <summary> /// Parses an instance of the specified type from the specified stream /// </summary> public object Parse(System.Xml.XmlReader s, Type useType, Type currentInteractionType, XmlIts1FormatterParseResult resultContext) { ConstructorInfo ci = useType.GetConstructor(Type.EmptyTypes); if(ci == null) throw new InvalidOperationException(String.Format("Cannot create an instance of type '{0}' as it defines no default constructor", useType.FullName)); // Create the instance object instance = ci.Invoke(null); PropertyInfo[] properties = useType.GetProperties(BindingFlags.Public | BindingFlags.Instance); // Move the reader to the first attribute if (s.MoveToFirstAttribute()) { // Now we read the attributes and match with the properties do { #if WINDOWS_PHONE PropertyInfo pi = properties.Find(o => o.GetCustomAttributes(true).Count(pa => pa is PropertyAttribute && (pa as PropertyAttribute).Name == s.LocalName) > 0); #else PropertyInfo pi = Array.Find<PropertyInfo>(properties, o => o.GetCustomAttributes(true).Count(pa => pa is PropertyAttribute && (pa as PropertyAttribute).Name == s.LocalName) > 0); #endif // Can we set the PI? if (s.LocalName == "ITSVersion" && s.Value != "XML_1.0") throw new System.InvalidOperationException(System.String.Format("This formatter can only parse XML_1.0 structures. This structure claims to be '{0}'.", s.Value)); else if (s.Prefix == "xmlns" || s.LocalName == "xmlns" || s.LocalName == "ITSVersion" || s.NamespaceURI == XmlIts1Formatter.NS_XSI) continue; else if (pi == null) { resultContext.AddResultDetail(new NotImplementedElementResultDetail(ResultDetailType.Warning, String.Format("@{0}", s.LocalName), s.NamespaceURI, s.ToString(), null)); continue; } var paList = pi.GetCustomAttributes(typeof(PropertyAttribute), true); // property attributes // VAlidate list of PA if(paList == null || paList.Length != 1) { resultContext.AddResultDetail(new ResultDetail(ResultDetailType.Warning, String.Format("Invalid number of PropertyAttributes on property '{0}', ignoring", pi.Name), s.ToString(), null)); continue; // not a property to be parsed } if (pi.GetSetMethod() == null) { if (!Util.ToWireFormat(pi.GetValue(instance, null)).Equals(s.Value)) resultContext.AddResultDetail(new FixedValueMisMatchedResultDetail(s.Value, pi.GetValue(instance, null).ToString(), true, s.ToString())); } else if (!String.IsNullOrEmpty((paList[0] as PropertyAttribute).FixedValue)) { if (!(paList[0] as PropertyAttribute).FixedValue.Equals(s.Value)) { resultContext.AddResultDetail(new FixedValueMisMatchedResultDetail(s.Value, (paList[0] as PropertyAttribute).FixedValue, false, s.ToString())); pi.SetValue(instance, Util.FromWireFormat(s.Value, pi.PropertyType), null); } } else pi.SetValue(instance, Util.FromWireFormat(s.Value, pi.PropertyType), null); } while (s.MoveToNextAttribute()); s.MoveToElement(); } // Nil? // BUG: Fixed, xsi:nil may also have a null-flavor String nil = s.GetAttribute("nil", XmlIts1Formatter.NS_XSI); if (!String.IsNullOrEmpty(nil) && Convert.ToBoolean(nil)) return instance; // Is reader at an empty element if (s.IsEmptyElement) return instance; // Read content string currentElementName = s.LocalName, lastElementRead = s.LocalName; while(true) { // End of stream or item not read if (lastElementRead == s.LocalName && !s.Read()) break; lastElementRead = s.LocalName; // Element is end element and matches the starting element namd if (s.NodeType == System.Xml.XmlNodeType.EndElement && s.LocalName == currentElementName) break; // Element is an end element //else if (s.NodeType == System.Xml.XmlNodeType.EndElement) // currentDepth--; // Element is a start element else if (s.NodeType == System.Xml.XmlNodeType.Element) { // Get the element choice property #if WINDOWS_PHONE PropertyInfo pi = properties.Find(o => o.GetCustomAttributes(true).Count(a => a is PropertyAttribute && (a as PropertyAttribute).Name == s.LocalName && ((a as PropertyAttribute).InteractionOwner ?? currentInteractionType) == currentInteractionType) > 0); #else PropertyInfo pi = Array.Find(properties, o => o.GetCustomAttributes(true).Count(a => a is PropertyAttribute && (a as PropertyAttribute).Name == s.LocalName && ((a as PropertyAttribute).InteractionOwner ?? currentInteractionType) == currentInteractionType) > 0); #endif if (pi == null) { resultContext.AddResultDetail(new NotImplementedElementResultDetail(ResultDetailType.Warning, s.LocalName, s.NamespaceURI, s.ToString(), null)); continue; } // Get the property attribute that defined the choice #if WINDOWS_PHONE PropertyAttribute pa = pi.GetCustomAttributes(true).Find(p => p is PropertyAttribute && (p as PropertyAttribute).Name == s.LocalName && ((p as PropertyAttribute).InteractionOwner ?? currentInteractionType) == currentInteractionType) as PropertyAttribute; #else PropertyAttribute pa = Array.Find(pi.GetCustomAttributes(true), p => p is PropertyAttribute && (p as PropertyAttribute).Name == s.LocalName && ((p as PropertyAttribute).InteractionOwner ?? currentInteractionType) == currentInteractionType) as PropertyAttribute; #endif // Can we set the PI? if (pi == null || !pi.CanWrite) continue; // Now time to set the PI if (String.IsNullOrEmpty(s.GetAttribute("specializationType")) && s is MARC.Everest.Xml.XmlStateReader && (this.Host.Settings & SettingsType.AllowFlavorImposing) == SettingsType.AllowFlavorImposing) (s as MARC.Everest.Xml.XmlStateReader).AddFakeAttribute("specializationType", pa.ImposeFlavorId); // Cannot deserialize this if (pa.Type == null && pi.PropertyType == typeof(System.Object)) resultContext.AddResultDetail(new NotImplementedElementResultDetail(ResultDetailType.Warning, pi.Name, pa.NamespaceUri, s.ToString(), null)); // Simple deserialization if PA type has IGraphable or PI type has IGraphable and PA type not specified else if (pi.GetSetMethod() != null && (pa.Type != null && pa.Type.GetInterface(typeof(IGraphable).FullName, false) != null) || (pa.Type == null && pi.PropertyType.GetInterface(typeof(IGraphable).FullName, false) != null)) { object tempFormat = Host.ParseObject(s, pa.Type ?? pi.PropertyType, currentInteractionType, resultContext); if (!String.IsNullOrEmpty(pa.FixedValue) && !pa.FixedValue.Equals(Util.ToWireFormat(tempFormat)) && pa.PropertyType != PropertyAttribute.AttributeAttributeType.Traversable) resultContext.AddResultDetail(new FixedValueMisMatchedResultDetail(Util.ToWireFormat(tempFormat), pa.FixedValue, s.ToString())); pi.SetValue(instance, Util.FromWireFormat(tempFormat, pa.Type ?? pi.PropertyType), null); } // Call an Add method on a collection type else if (pi.PropertyType.GetMethod("Add") != null) // Collection type pi.PropertyType.GetMethod("Add").Invoke(pi.GetValue(instance, null), new object[] { Util.FromWireFormat(Host.ParseObject(s, pi.PropertyType.GetGenericArguments()[0], currentInteractionType, resultContext), pi.PropertyType.GetGenericArguments()[0]) }); // Call the ParseXML custom function on object else if (pi.GetSetMethod() != null && pi.PropertyType.GetMethod("ParseXml", BindingFlags.Public | BindingFlags.Static) != null) pi.SetValue(instance, pi.PropertyType.GetMethod("ParseXml").Invoke(instance, new object[] { s }), null); // Property type is a simple string else if (pi.GetSetMethod() != null && pi.PropertyType == typeof(string)) // Read content... pi.SetValue(instance, Util.FromWireFormat(s.ReadInnerXml(), typeof(String)), null); // No Set method is used, fixed value? else { object tempFormat = Host.ParseObject(s, pa.Type ?? pi.PropertyType, currentInteractionType, resultContext); if (tempFormat.ToString() != pi.GetValue(instance, null).ToString() && pa.PropertyType != PropertyAttribute.AttributeAttributeType.Traversable) resultContext.AddResultDetail(new MARC.Everest.Connectors.FixedValueMisMatchedResultDetail(tempFormat.ToString(), pi.GetValue(instance, null).ToString(), s.ToString())); } } } return instance; }
protected override void DeserializeElement(System.Xml.XmlReader reader, bool serializeCollectionKey) { Value = reader.ReadInnerXml(); }