ReadElementContentAs() public méthode

public ReadElementContentAs ( Type returnType, IXmlNamespaceResolver namespaceResolver ) : object
returnType System.Type
namespaceResolver IXmlNamespaceResolver
Résultat object
Exemple #1
0
		internal static ResolveCriteria ReadXml (XmlReader reader, DiscoveryVersion version)
		{
			if (reader == null)
				throw new ArgumentNullException ("reader");

			var ret = new ResolveCriteria ();

			reader.MoveToContent ();
			if (!reader.IsStartElement ("ResolveType", version.Namespace) || reader.IsEmptyElement)
				throw new XmlException ("Non-empty ResolveType element is expected");
			reader.ReadStartElement ("ResolveType", version.Namespace);

			// standard members
			reader.MoveToContent ();
			ret.Address = EndpointAddress.ReadFrom (version.MessageVersion.Addressing, reader);

			// non-standard members
			for (reader.MoveToContent (); !reader.EOF && reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
				if (reader.NamespaceURI == SerializationNS) {
					switch (reader.LocalName) {
					case "Duration":
						ret.Duration = (TimeSpan) reader.ReadElementContentAs (typeof (TimeSpan), null);
						break;
					}
				}
				else
					ret.Extensions.Add (XElement.Load (reader));
			}

			reader.ReadEndElement ();

			return ret;
		}
Exemple #2
0
        protected override void DeserializeElement(XmlReader reader, bool s)
        {
            // ReSharper disable AssignNullToNotNullAttribute
            Value = reader.ReadElementContentAs(typeof(string), null) as string;
            // ReSharper restore AssignNullToNotNullAttribute

            if (Value != null) Value = Value.Trim();
        }
		internal static EndpointDiscoveryMetadata ReadXml (XmlReader reader, DiscoveryVersion version)
		{
			if (reader == null)
				throw new ArgumentNullException ("reader");

			var ret = new EndpointDiscoveryMetadata ();

			reader.MoveToContent ();

			reader.ReadStartElement ();
			reader.MoveToContent ();

			// standard members
			reader.MoveToContent ();

			// it is possible due to InternalVisibleToAttribute...
			string addrNS = version.MessageVersion.Addressing.Namespace;

			ret.Address = EndpointAddress.ReadFrom (version.MessageVersion.Addressing, reader, "EndpointReference", addrNS);

			reader.MoveToContent ();
			if (reader.IsStartElement ("Types", version.Namespace))
				ret.ContractTypeNames = new Collection<XmlQualifiedName> ((XmlQualifiedName []) reader.ReadElementContentAs (typeof (XmlQualifiedName []), null, "Types", version.Namespace));

			reader.MoveToContent ();
			if (reader.IsStartElement ("Scopes", version.Namespace))
				ret.Scopes = new Collection<Uri> ((Uri []) reader.ReadElementContentAs (typeof (Uri []), null, "Scopes", version.Namespace));

			if (reader.IsStartElement ("XAddrs", version.Namespace))
				ret.ListenUris = new Collection<Uri> ((Uri []) reader.ReadElementContentAs (typeof (Uri []), null, "XAddrs", version.Namespace));

			if (reader.IsStartElement ("MetadataVersion", version.Namespace))
				ret.Version = reader.ReadElementContentAsInt ();

			// non-standard members
			for (reader.MoveToContent (); !reader.EOF && reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ())
				ret.Extensions.Add (XElement.Load (reader));

			reader.ReadEndElement ();

			return ret;
		}
		internal static EndpointDiscoveryMetadata ReadXml (XmlReader reader, DiscoveryVersion version)
		{
			if (reader == null)
				throw new ArgumentNullException ("reader");

			var ret = new EndpointDiscoveryMetadata ();

			reader.MoveToContent ();
			if (!reader.IsStartElement ("ProbeMatchType", version.Namespace) || reader.IsEmptyElement)
				throw new XmlException ("Non-empty ProbeMatchType element is expected");
			reader.ReadStartElement ("ProbeType", version.Namespace);

			// standard members
			reader.MoveToContent ();
			ret.Address = EndpointAddress.ReadFrom (AddressingVersion.WSAddressing10, reader);

			reader.MoveToContent ();
			bool isEmpty = reader.IsEmptyElement;
			ret.ContractTypeNames = new Collection<XmlQualifiedName> ((XmlQualifiedName []) reader.ReadElementContentAs (typeof (XmlQualifiedName []), null, "Types", version.Namespace));

			reader.MoveToContent ();
			if (reader.IsStartElement ("Scopes", version.Namespace))
				ret.Scopes = new Collection<Uri> ((Uri []) reader.ReadElementContentAs (typeof (Uri []), null, "Scopes", version.Namespace));

			if (reader.IsStartElement ("XAddrs", version.Namespace))
				ret.ListenUris = new Collection<Uri> ((Uri []) reader.ReadElementContentAs (typeof (Uri []), null, "XAddrs", version.Namespace));

			if (reader.IsStartElement ("MetadataVersion", version.Namespace))
				ret.Version = reader.ReadElementContentAsInt ();

			// non-standard members
			for (reader.MoveToContent (); !reader.EOF && reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ())
				ret.Extensions.Add (XElement.Load (reader));

			reader.ReadEndElement ();

			return ret;
		}
 protected override void DeserializeElement(XmlReader reader, bool serializeCollectionKey)
 {
     var props = Properties;
     if (reader.AttributeCount > 0)
     {
         while (reader.MoveToNextAttribute())
         {
             var propertyName = reader.Name;
             var xmlValue = reader.Value;
             var prop = props[propertyName];
             var propertyValue = prop.Converter.ConvertFromInvariantString(xmlValue);
             base[propertyName] = propertyValue;
         }
     }
     reader.MoveToContent();
     var content = reader.ReadElementContentAs(typeof(string), null);
     if (content != null)
         Sql = ((string)content).Trim();
 }
 private void ParseBlock(ref List<MemoryBlock> list, ref XmlReader reader)
 {
     MemoryBlock MemBlock = new MemoryBlock();
     reader.ReadToFollowing("m_block_base_addr");
     MemBlock.BlockAddress = (UInt64)reader.ReadElementContentAs(typeof(UInt64), null);
     reader.ReadToNextSibling("protection");
     MemBlock.BlockProtection = (UInt32)reader.ReadElementContentAs(typeof(UInt32), null);
     reader.ReadToNextSibling("m_size");
     MemBlock.BlockSize = (UInt64)reader.ReadElementContentAs(typeof(UInt64), null);
     reader.ReadToNextSibling("m_storage_type");
     MemBlock.BlockStorageType = (UInt32)reader.ReadElementContentAs(typeof(UInt32), null);
     reader.ReadToNextSibling("m_is_shared");
     MemBlock.IsShared = (Boolean)reader.ReadElementContentAs(typeof(Boolean), null);
     reader.ReadToNextSibling("m_map_file_name");
     MemBlock.MappedFileName = (String)reader.ReadElementContentAs(typeof(String), null);
     list.Add(MemBlock);
 }
 /// <summary>
 /// Deserializes the contents of the given XML <paramref name="reader"/>'s current element in the formatting rules
 /// given by this data type.
 /// </summary>
 /// <param name="reader">XML reader whose current element's value will be deserialized.
 /// The reader's position is the start of the parent element, the result should go. After this method returns, the reader
 /// must have read the end element.</param>
 /// <returns>Deserialized object of this data type (may be <c>null</c>).</returns>
 public object SoapDeserializeValue(XmlReader reader)
 {
   object result;
   if (SoapHelper.ReadNull(reader))
     result = null;
   else
   {
     switch (_upnpTypeName)
     {
       case "ui1":
       case "ui2":
       case "ui4":
       case "ui8":
       case "i1":
       case "i2":
       case "i4":
       case "i8":
       case "int":
       case "r4":
       case "r8":
       case "number":
       case "fixed.14.4":
       case "float":
       case "char":
         result = reader.ReadElementContentAs(_dotNetType, null);
         break;
       case "string":
       case "uuid":
         result = reader.ReadElementContentAsString();
         break;
       case "date":
         result = System.DateTime.ParseExact(reader.ReadElementContentAsString(), "yyyy-MM-dd", null);
         break;
       case "dateTime":
         result = System.DateTime.ParseExact(reader.ReadElementContentAsString(), "s", null);
         break;
       case "dateTime.tz":
         result = System.DateTime.ParseExact(reader.ReadElementContentAsString(), "u", null).ToLocalTime();
         break;
       case "time":
         result = System.DateTime.ParseExact(reader.ReadElementContentAsString(), "T", null);
         break;
       case "time.tz":
         result = System.DateTime.ParseExact(reader.ReadElementContentAsString(), "hh:mm:ss", null).ToLocalTime();
         break;
       case "boolean":
         result = reader.ReadElementContentAs(_dotNetType, null);
         break;
       case "bin.base64":
         result = reader.ReadElementContentAs(_dotNetType, null);
         break;
       case "bin.hex":
         result = EncodingUtils.FromHexString(reader.ReadElementContentAsString());
         break;
       case "uri":
         result = new Uri(reader.ReadElementContentAsString());
         break;
       default:
         throw new NotImplementedException(string.Format("UPnP standard data type '{0}' is not implemented", _upnpTypeName));
     }
     // Reader will already have read the end element in the methods ReadElementContentXXX
   }
   return result;
 }
 public override object ReadElementContentAs(Type returnType, IXmlNamespaceResolver namespaceResolver)
 {
     CheckAsync();
     return(_coreReader.ReadElementContentAs(returnType, namespaceResolver));
 }
        private static object ReadValue(XmlReader reader, Type objectType, string name)
        {
            object value = null;
            var hasValue = false;
            if (name != null && reader.HasAttributes)
            {
                var attrValue = reader.GetAttribute(name);
                hasValue = !string.IsNullOrEmpty(attrValue);
                attrValue.TryParse(objectType, out value);
            }

            if (!hasValue)
            {
                value = reader.ReadElementContentAs(objectType, null);
            }
            return value;
        }
 protected override void DeserializeElement(XmlReader reader, bool serializeCollectionKey)
 {
     Value = (string)reader.ReadElementContentAs(typeof(string), null);
 }
 private void ParseRegion(ref MemoryRegion region, ref XmlReader reader)
 {
     reader.ReadToDescendant("m_region_base_addr");
     region.RegionAddress = (UInt64)reader.ReadElementContentAs(typeof(UInt64), null);
     reader.ReadToNextSibling("m_region_protection");
     region.RegionProtection = (UInt32)reader.ReadElementContentAs(typeof(UInt32), null);
     reader.ReadToNextSibling("region_size");
     region.RegionSize = (UInt64)reader.ReadElementContentAs(typeof(UInt64), null);
     reader.ReadToNextSibling("m_storage_type");
     region.RegionStorageType = (UInt32)reader.ReadElementContentAs(typeof(UInt32), null);
     reader.ReadToNextSibling("m_region_blocks");
     region.NumberOfBlocks = (UInt32)reader.ReadElementContentAs(typeof(UInt32), null);
     reader.ReadToNextSibling("m_guard_blocks");
     region.NumberOfGuardBlocks = (UInt32)reader.ReadElementContentAs(typeof(UInt32), null);
     reader.ReadToNextSibling("m_is_stack");
     region.IsAStack = (Boolean)reader.ReadElementContentAs(typeof(Boolean), null);
     reader.ReadToFollowing("m_blocks");
     XmlReader SubReader = reader.ReadSubtree();
     ParseBlocks(ref region.MemoryBlocks, ref SubReader);
 }
Exemple #12
0
        public virtual void ReadXml(System.Xml.XmlReader reader)
        {
            if (reader.ReadToDescendant("LotsOfData") == false)
            {
                throw new Exception("could not find the start of element LotsOfData");
            }

            if (reader.ReadToDescendant("Boolean") == false)
            {
                throw new Exception("could not find the start of element Boolean");
            }

            reader.Read();
            if (reader.ReadContentAsBoolean() == false)
            {
                throw new Exception("did not find the correct value in Boolean");
            }

            //DateTime
            if (reader.ReadToNextSibling("DateTime") == false)
            {
                throw new Exception("could not find the start of element DateTime");
            }

            reader.Read();
            DateTime now = reader.ReadContentAsDateTime();

            if (now != Now)
            {
                TimeSpan diff = new TimeSpan((now.Ticks - Now.Ticks));
                if (diff.TotalMilliseconds > 1000)
                {
                    // seconds are lost in Xml
                    throw new Exception(String.Format("Dates differ {0} {1} Ticks {2}", now, Now, (now.Ticks - Now.Ticks)));
                }
            }

            //DecimalValue
            if (reader.ReadToNextSibling("DecimalValue") == false)
            {
                throw new Exception("could not find the start of element DecimalValue");
            }
            //			reader.Read();
            decimal decimalValue = (decimal)reader.ReadElementContentAs(typeof(decimal), null);

            if (decimalValue != CommonUtilities.DecimalValue)
            {
                string msg = String.Format("different decimal Values {0} {1}", decimalValue, CommonUtilities.DecimalValue);
                throw new Exception(msg);
            }

            //DoubleValue
            if (reader.NodeType != System.Xml.XmlNodeType.Element && reader.Name != "DoubleValue")
            {
                if (reader.ReadToNextSibling("DoubleValue") == false)
                {
                    throw new Exception("could not find the start of element DoubleValue");
                }
            }

            //reader.Read();
            double doubleValue = (double)reader.ReadElementContentAsDouble();

            if (doubleValue != CommonUtilities.DoubleValue)
            {
                string msg = String.Format("different double Values {0} {1}", doubleValue, CommonUtilities.DoubleValue);
                throw new Exception(msg);
            }

            //FloatValue
            if (reader.NodeType != System.Xml.XmlNodeType.Element && reader.Name != "FloatValue")
            {
                if (reader.ReadToNextSibling("FloatValue") == false)
                {
                    throw new Exception("could not find the start of element FloatValue");
                }
            }

            //reader.Read();
            float floatValue = (float)reader.ReadElementContentAs(typeof(float), null);

            if (floatValue != CommonUtilities.FloatValue)
            {
                string msg = String.Format("different floatValue Values {0} {1}", floatValue, CommonUtilities.FloatValue);
                throw new MyException(msg);
            }

            //IntValue
            if (reader.NodeType != System.Xml.XmlNodeType.Element && reader.Name != "IntValue")
            {
                if (reader.ReadToNextSibling("IntValue") == false)
                {
                    throw new Exception("could not find the start of element IntValue");
                }
            }
            //			reader.Read();
            int intValue = reader.ReadElementContentAsInt();

            if (intValue != CommonUtilities.IntValue)
            {
                string msg = String.Format("different intValue Values {0} {1}", intValue, CommonUtilities.IntValue);
                throw new MyException(msg);
            }

            //LongValue
            if (reader.NodeType != System.Xml.XmlNodeType.Element && reader.Name != "LongValue")
            {
                if (reader.ReadToNextSibling("LongValue") == false)
                {
                    throw new Exception("could not find the start of element LongValue");
                }
            }
            //reader.Read();
            long longValue = (long)reader.ReadElementContentAs(typeof(long), null);

            if (longValue != CommonUtilities.LongValue)
            {
                string msg = String.Format("different longValue Values {0} {1}", longValue, CommonUtilities.LongValue);
                throw new MyException(msg);
            }

            //Object
            if (reader.NodeType != System.Xml.XmlNodeType.Element && reader.Name != "Object")
            {
                if (reader.ReadToNextSibling("Object") == false)
                {
                    throw new MyException("could not find the start of element Object");
                }
            }

            //reader.Read();
            TimeSpan objectValue = (TimeSpan)reader.ReadElementContentAs(typeof(TimeSpan), null);

            if (objectValue != CommonUtilities.TimeSpanValue)
            {
                string msg = String.Format("different objectValue Values {0} {1}", objectValue, CommonUtilities.TimeSpanValue);
                throw new MyException(msg);
            }

            //StringValue
            if (reader.NodeType != System.Xml.XmlNodeType.Element && reader.Name != "StringValue")
            {
                if (reader.ReadToNextSibling("StringValue") == false)
                {
                    throw new MyException("could not find the start of element StringValue");
                }
            }

            //reader.Read();
            string stringValue = reader.ReadElementContentAsString();

            if (stringValue == null || stringValue.Equals(CommonUtilities.XmlStringForAttributes) == false)
            {
                string msg = String.Format("different stringValue Values {0} {1}", stringValue, CommonUtilities.XmlStringForAttributes);
                throw new MyException(msg);
            }

            int       counter      = 0;
            const int NODES_AT_END = 1;

            while (reader.Read())
            {
                counter++;
            }

            if (counter != NODES_AT_END)
            {
                throw new MyException(String.Format("expected {0} nodes, but found {1}", NODES_AT_END, counter));
            }
        }
        /// <summary>
        /// Deserializes the current BusinessObject from a XML stream.
        /// </summary>
        /// <param name="r">Active XML stream reader.</param>
        /// <remarks>Reads the outer element. Leaves the reader at the same depth.</remarks>
        // TODO Clear properties before reading from file
        public virtual void ReadXml(XmlReader r)
        {
            var props = GetAllDataProperties().ToList();
            r.ReadStartElement();
            while (r.NodeType == XmlNodeType.Element) {

                var prop = props.FirstOrDefault(n => n.Name.Equals(r.Name));
                if (prop == null) {
                    // ignore unknown property.
                    r.Skip();
                    continue;
                }

                var propertyType = prop.PropertyType;
                var propertyValue = prop.GetValue(this, null);

                // if property type is BusinessObject, let it auto-load from XML.
                if (typeof(BusinessObject).IsAssignableFrom(propertyType)) {
                    ((BusinessObject)propertyValue).ReadXml(r);
                    continue;
                }

                // if property type is List<T>, assume it's of BusinessObjects and try to fetch them from XML.
                var tList = typeof (List<>);
                if (propertyType.IsGenericType && tList.IsAssignableFrom(propertyType.GetGenericTypeDefinition()) ||
                    propertyType.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == tList)) {
                    ReadXmlList(propertyValue, prop.Name, r);
                    continue;
                }

                if (typeof(DateTime?).IsAssignableFrom(propertyType)) {
                    // ReadElementContentAs won't accept a nullable DateTime.
                    propertyType = typeof(DateTime);
                }
                // ReSharper disable once AssignNullToNotNullAttribute
                prop.SetValue(this, r.ReadElementContentAs(propertyType, null), null);
            }
            r.ReadEndElement();
        }
Exemple #14
0
		internal static FindCriteria ReadXml (XmlReader reader, DiscoveryVersion version)
		{
			if (reader == null)
				throw new ArgumentNullException ("reader");

			var ret = new FindCriteria ();

			reader.MoveToContent ();
			if (!reader.IsStartElement ("Probe", version.Namespace) || reader.IsEmptyElement)
				throw new XmlException (String.Format ("Non-empty ProbeType element is expected. Got '{0}' {1} node in namespace '{2}' instead.", reader.LocalName, reader.NodeType, reader.NamespaceURI));
			reader.ReadStartElement ("Probe", version.Namespace);

			// standard members
			reader.MoveToContent ();
			if (reader.IsStartElement ("Types", version.Namespace))
				ret.ContractTypeNames = new Collection<XmlQualifiedName> ((XmlQualifiedName []) reader.ReadElementContentAs (typeof (XmlQualifiedName []), null, "Types", version.Namespace));

			reader.MoveToContent ();
			if (reader.IsStartElement ("Types", version.Namespace)) {
				if (reader.MoveToAttribute ("MatchBy")) {
					ret.ScopeMatchBy = new Uri (reader.Value, UriKind.RelativeOrAbsolute);
					reader.MoveToElement ();
				}
				ret.Scopes = new Collection<Uri> ((Uri []) reader.ReadElementContentAs (typeof (Uri []), null, "Scopes", version.Namespace));
			}

			// non-standard members
			for (reader.MoveToContent (); !reader.EOF && reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
				if (reader.NamespaceURI == SerializationNS) {
					switch (reader.LocalName) {
					case "MaxResults":
						ret.MaxResults = reader.ReadElementContentAsInt ();
						break;
					case "Duration":
						ret.Duration = (TimeSpan) reader.ReadElementContentAs (typeof (TimeSpan), null);
						break;
					}
				}
				else
					ret.Extensions.Add (XElement.Load (reader));
			}

			reader.ReadEndElement ();

			return ret;
		}
 private void ParseBlocks(ref List<MemoryBlock> list, ref XmlReader reader)
 {
     reader.ReadToFollowing("count");
     UInt32 ListLength = (UInt32)reader.ReadElementContentAs(typeof(UInt32), null);
     if (ListLength == 0)
         return;
     list = new List<MemoryBlock>();
     while (reader.ReadToFollowing("item"))
     {
         XmlReader SubReader = reader.ReadSubtree();
         ParseBlock(ref list, ref SubReader);
     }
 }
 /// <summary>
 /// Deserializes the element.
 /// </summary>
 /// <param name="reader">The reader.</param>
 /// <param name="s">if set to <c>true</c> [s].</param>
 protected override void DeserializeElement(XmlReader reader, bool s)
 {
     this.Value = reader.ReadElementContentAs(typeof(string), null) as string;
 }
        public static void ReadObjectProperties(XmlReader reader, object obj, PropertyConversionHandler handler = null)
        {
            // Build property lookup table
            PropertyInfo[] props = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
            Dictionary<string, PropertyInfo> propHash = new Dictionary<string, PropertyInfo>(props.Length);
            foreach (var pi in props)
                if (!Attribute.IsDefined(pi, typeof(XmlIgnoreAttribute), false))
                    propHash.Add(GetPropertyElementName(pi), pi);

            while (reader.MoveToContent() == System.Xml.XmlNodeType.Element)
            {
                PropertyInfo pi;
                if (propHash.TryGetValue(reader.LocalName, out pi))
                {
                    if (IsStandardType(pi.PropertyType))
                    {
                        object value = null;
                        if (pi.PropertyType.IsEnum)
                            value = Enum.Parse(pi.PropertyType, reader.ReadElementContentAsString());
                        else
                            value = reader.ReadElementContentAs(pi.PropertyType, null);

                        if (handler != null)
                            handler(pi, obj, ref value);

                        pi.SetValue(obj, value, null);
                    }
                    else
                    {
                        ReadObject(reader, pi.GetValue(obj, null));
                    }
                }
                else
                {
                    reader.Skip();
                    reader.MoveToContent();
                }
            }
        }