XmlSerializer.cs 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274
  1. //
  2. // Mono Class Libraries
  3. // System.Xml.Serialization.XmlSerializer
  4. //
  5. // Authors:
  6. // John Donagher ([email protected])
  7. // Ajay kumar Dwivedi ([email protected])
  8. // Tim Coleman ([email protected])
  9. // Elan Feingold ([email protected])
  10. //
  11. // (C) 2002 John Donagher, Ajay kumar Dwivedi
  12. // Copyright (C) Tim Coleman, 2002
  13. // (C) 2003 Elan Feingold
  14. //
  15. using System;
  16. using System.Collections;
  17. using System.IO;
  18. using System.Reflection;
  19. using System.Xml;
  20. using System.Xml.Schema;
  21. using System.Text;
  22. namespace System.Xml.Serialization {
  23. /// <summary>
  24. /// Summary description for XmlSerializer.
  25. /// </summary>
  26. public class XmlSerializer {
  27. #region Fields
  28. Type xsertype;
  29. XmlAttributeOverrides overrides;
  30. Type[] extraTypes;
  31. XmlRootAttribute rootAttribute;
  32. string defaultNamespace;
  33. Hashtable typeTable;
  34. bool useOrder;
  35. bool isNullable;
  36. Hashtable typeMappings = new Hashtable ();
  37. #endregion // Fields
  38. #region Constructors
  39. protected XmlSerializer ()
  40. {
  41. }
  42. public XmlSerializer (Type type)
  43. : this (type, null, null, null, null)
  44. {
  45. }
  46. public XmlSerializer (XmlTypeMapping xmlTypeMapping)
  47. {
  48. typeMappings.Add (xmlTypeMapping.TypeFullName, xmlTypeMapping);
  49. }
  50. public XmlSerializer (Type type, string defaultNamespace)
  51. : this (type, null, null, null, defaultNamespace)
  52. {
  53. }
  54. public XmlSerializer (Type type, Type[] extraTypes)
  55. : this (type, null, extraTypes, null, null)
  56. {
  57. }
  58. public XmlSerializer (Type type, XmlAttributeOverrides overrides)
  59. : this (type, overrides, null, null, null)
  60. {
  61. }
  62. public XmlSerializer (Type type, XmlRootAttribute root)
  63. : this (type, null, null, root, null)
  64. {
  65. }
  66. internal XmlSerializer (Hashtable typeTable)
  67. {
  68. this.typeTable = typeTable;
  69. }
  70. public XmlSerializer (Type type,
  71. XmlAttributeOverrides overrides,
  72. Type [] extraTypes,
  73. XmlRootAttribute root,
  74. string defaultNamespace)
  75. {
  76. if (type == null)
  77. throw new ArgumentNullException ("type");
  78. XmlReflectionImporter ri = new XmlReflectionImporter (overrides, defaultNamespace);
  79. TypeData td = TypeTranslator.GetTypeData (type);
  80. typeMappings.Add (td.FullTypeName, ri.ImportTypeMapping (type, root, defaultNamespace));
  81. ri.IncludeTypes (type);
  82. if (extraTypes != null) {
  83. foreach (Type t in extraTypes) {
  84. td = TypeTranslator.GetTypeData (t);
  85. string n = td.FullTypeName;
  86. typeMappings.Add (n, ri.ImportTypeMapping (type, root, defaultNamespace));
  87. ri.IncludeTypes (t);
  88. }
  89. }
  90. this.xsertype = type;
  91. this.overrides = overrides;
  92. this.extraTypes = (extraTypes == null ? new Type[0] : extraTypes);
  93. if (root != null)
  94. this.rootAttribute = root;
  95. else {
  96. object[] attributes = type.GetCustomAttributes (typeof (XmlRootAttribute), false);
  97. if (attributes.Length > 0)
  98. this.rootAttribute = (XmlRootAttribute) attributes[0];
  99. }
  100. this.defaultNamespace = defaultNamespace;
  101. if (typeTable == null)
  102. typeTable = new Hashtable ();
  103. FillTypeTable (type);
  104. }
  105. #endregion // Constructors
  106. #region Events
  107. public event XmlAttributeEventHandler UnknownAttribute;
  108. public event XmlElementEventHandler UnknownElement;
  109. public event XmlNodeEventHandler UnknownNode;
  110. public event UnreferencedObjectEventHandler UnreferencedObject;
  111. #endregion // Events
  112. #region Properties
  113. internal bool UseOrder {
  114. get { return useOrder; }
  115. set { useOrder = value; }
  116. }
  117. #endregion // Properties
  118. #region Methods
  119. [MonoTODO]
  120. public virtual bool CanDeserialize (XmlReader xmlReader)
  121. {
  122. throw new NotImplementedException ();
  123. }
  124. protected virtual XmlSerializationReader CreateReader ()
  125. {
  126. // This is what MS does!!!
  127. throw new NotImplementedException ();
  128. }
  129. protected virtual XmlSerializationWriter CreateWriter ()
  130. {
  131. // This is what MS does!!!
  132. throw new NotImplementedException ();
  133. }
  134. public object Deserialize (Stream stream)
  135. {
  136. XmlTextReader xmlReader = new XmlTextReader(stream);
  137. return Deserialize(xmlReader);
  138. }
  139. public object Deserialize (TextReader textReader)
  140. {
  141. XmlTextReader xmlReader = new XmlTextReader(textReader);
  142. return Deserialize(xmlReader);
  143. }
  144. public bool DeserializeComposite(XmlReader xmlReader, ref Object theObject)
  145. {
  146. Type objType = theObject.GetType();
  147. bool retVal = true;
  148. //Console.WriteLine("DeserializeComposite({0})", objType);
  149. // Are we at an empty element?
  150. if (xmlReader.IsEmptyElement == true)
  151. return retVal;
  152. // Read each field, counting how many we find.
  153. for (int numFields=0; xmlReader.Read(); )
  154. {
  155. XmlNodeType xmlNodeType = xmlReader.NodeType;
  156. bool isEmpty = xmlReader.IsEmptyElement;
  157. if (xmlNodeType == XmlNodeType.Element)
  158. {
  159. // Read the field.
  160. DeserializeField(xmlReader, ref theObject, xmlReader.Name);
  161. numFields++;
  162. }
  163. else if (xmlNodeType == XmlNodeType.EndElement)
  164. {
  165. if (numFields == 0)
  166. {
  167. //Console.WriteLine("Empty object deserialized, ignoring.");
  168. retVal = false;
  169. }
  170. return retVal;
  171. }
  172. }
  173. return retVal;
  174. }
  175. public void DeserializeField (XmlReader xmlReader, ref Object theObject, String fieldName)
  176. {
  177. //Console.WriteLine("DeserializeField({0})", fieldName);
  178. BindingFlags bindingFlags = 0;
  179. Type fieldType = null;
  180. // Get the type, first try a field.
  181. FieldInfo fieldInfo = theObject.GetType().GetField(fieldName);
  182. if (fieldInfo != null) {
  183. fieldType = fieldInfo.FieldType;
  184. bindingFlags = BindingFlags.SetField;
  185. } else {
  186. // Is it a property?
  187. PropertyInfo propInfo = theObject.GetType().GetProperty(fieldName);
  188. if (propInfo != null)
  189. {
  190. fieldType = propInfo.PropertyType;
  191. bindingFlags = BindingFlags.SetProperty;
  192. }
  193. }
  194. if (fieldType == null)
  195. throw new Exception (String.Format ("On type {0} can not identify {1}", theObject.GetType (), fieldName));
  196. Object value = null;
  197. bool isEmptyField = xmlReader.IsEmptyElement;
  198. //Console.WriteLine("DeserializeField({0} of type {1})", fieldName, fieldType);
  199. if (fieldType.IsArray && fieldType != typeof(System.Byte[]))
  200. {
  201. // Create an empty array list.
  202. ArrayList list = new ArrayList();
  203. // Call out to deserialize it.
  204. DeserializeArray(xmlReader, list, fieldType.GetElementType());
  205. value = list.ToArray(fieldType.GetElementType());
  206. }
  207. else if (isEmptyField == false && (IsInbuiltType(fieldType) || fieldType.IsEnum || fieldType.IsArray))
  208. {
  209. // Built in, set it.
  210. while (xmlReader.Read())
  211. {
  212. if (xmlReader.NodeType == XmlNodeType.Text)
  213. {
  214. //Console.WriteLine(" -> value is '{0}'", xmlReader.Value);
  215. if (fieldType == typeof(Guid))
  216. value = XmlConvert.ToGuid(xmlReader.Value);
  217. else if (fieldType == typeof(Boolean))
  218. value = XmlConvert.ToBoolean(xmlReader.Value);
  219. else if (fieldType == typeof(String))
  220. value = xmlReader.Value;
  221. else if (fieldType == typeof(Int64))
  222. value = XmlConvert.ToInt64(xmlReader.Value);
  223. else if (fieldType == typeof(DateTime))
  224. value = XmlConvert.ToDateTime(xmlReader.Value);
  225. else if (fieldType.IsEnum)
  226. value = Enum.Parse(fieldType, xmlReader.Value);
  227. else if (fieldType == typeof(System.Byte[]))
  228. value = XmlCustomFormatter.ToByteArrayBase64(xmlReader.Value);
  229. else if (fieldType == typeof (Int32))
  230. value = XmlConvert.ToInt32 (xmlReader.Value);
  231. else
  232. Console.WriteLine("XmlSerializer.DeserializeField, improve routine: Error (type is '{0}')", fieldType);
  233. break;
  234. }
  235. }
  236. }
  237. else if (isEmptyField == true)
  238. {
  239. if (fieldType.IsArray)
  240. {
  241. // Must be a byte array, just create an empty one.
  242. value = new byte[0];
  243. }
  244. else if (fieldType == typeof(string))
  245. {
  246. // Create a new empty string.
  247. value = "";
  248. }
  249. }
  250. else
  251. {
  252. //Console.WriteLine("Creating new {0}", fieldType);
  253. // Create the new complex object.
  254. value = System.Activator.CreateInstance(fieldType);
  255. // Recurse, allowing the method to whack the object if it's empty.
  256. DeserializeComposite(xmlReader, ref value);
  257. }
  258. //Console.WriteLine(" Setting {0} to '{1}'", fieldName, value);
  259. // Set the field value.
  260. theObject.GetType().InvokeMember(fieldName,
  261. bindingFlags,
  262. null,
  263. theObject,
  264. new Object[] { value },
  265. null, null, null);
  266. // We need to munch the end.
  267. if (IsInbuiltType(fieldType) ||
  268. fieldType.IsEnum ||
  269. fieldType == typeof(System.Byte[]))
  270. {
  271. if (isEmptyField == false)
  272. while (xmlReader.Read() && xmlReader.NodeType != XmlNodeType.EndElement)
  273. ;
  274. }
  275. }
  276. public void DeserializeArray(XmlReader xmlReader, ArrayList theList, Type theType)
  277. {
  278. //Console.WriteLine(" DeserializeArray({0})", theType);
  279. if (xmlReader.IsEmptyElement)
  280. {
  281. //Console.WriteLine(" DeserializeArray -> empty, nothing to do here");
  282. return;
  283. }
  284. while (xmlReader.Read())
  285. {
  286. XmlNodeType xmlNodeType = xmlReader.NodeType;
  287. bool isEmpty = xmlReader.IsEmptyElement;
  288. if (xmlNodeType == XmlNodeType.Element)
  289. {
  290. // Must be an element of the array, create it.
  291. Object obj = System.Activator.CreateInstance(theType);
  292. //Console.WriteLine(" created obj of type '{0}'", obj.GetType());
  293. // Deserialize and add.
  294. if (DeserializeComposite(xmlReader, ref obj))
  295. {
  296. theList.Add(obj);
  297. }
  298. }
  299. if ((xmlNodeType == XmlNodeType.Element && isEmpty) ||
  300. (xmlNodeType == XmlNodeType.EndElement))
  301. {
  302. return;
  303. }
  304. }
  305. }
  306. public object Deserialize(XmlReader xmlReader)
  307. {
  308. Object obj = null;
  309. // Read each node in the tree.
  310. while (xmlReader.Read())
  311. {
  312. if (xmlReader.NodeType == XmlNodeType.Element)
  313. {
  314. // Create the top level object.
  315. //Console.WriteLine("Creating '{0}'", xsertype.FullName);
  316. obj = System.Activator.CreateInstance(xsertype);
  317. // Deserialize it.
  318. DeserializeComposite(xmlReader, ref obj);
  319. }
  320. else if (xmlReader.NodeType == XmlNodeType.EndElement)
  321. {
  322. return obj;
  323. }
  324. }
  325. return obj;
  326. }
  327. protected virtual object Deserialize (XmlSerializationReader reader)
  328. {
  329. // This is what MS does!!!
  330. throw new NotImplementedException ();
  331. }
  332. [MonoTODO]
  333. public static XmlSerializer [] FromMappings (XmlMapping [] mappings)
  334. {
  335. throw new NotImplementedException ();
  336. }
  337. [MonoTODO]
  338. public static XmlSerializer [] FromTypes (Type [] mappings)
  339. {
  340. throw new NotImplementedException ();
  341. }
  342. [MonoTODO]
  343. protected virtual void Serialize (object o, XmlSerializationWriter writer)
  344. {
  345. throw new NotImplementedException ();
  346. }
  347. public void Serialize (Stream stream, object o)
  348. {
  349. XmlTextWriter xmlWriter = new XmlTextWriter (stream, System.Text.Encoding.Default);
  350. xmlWriter.Formatting = Formatting.Indented;
  351. Serialize (xmlWriter, o, null);
  352. xmlWriter.WriteEndDocument();
  353. xmlWriter.Flush();
  354. }
  355. public void Serialize (TextWriter textWriter, object o)
  356. {
  357. XmlTextWriter xmlWriter = new XmlTextWriter (textWriter);
  358. xmlWriter.Formatting = Formatting.Indented;
  359. Serialize (xmlWriter, o, null);
  360. xmlWriter.WriteEndDocument();
  361. xmlWriter.Flush();
  362. }
  363. public void Serialize (XmlWriter xmlWriter, object o)
  364. {
  365. Serialize (xmlWriter, o, null);
  366. }
  367. public void Serialize (Stream stream, object o, XmlSerializerNamespaces namespaces)
  368. {
  369. XmlTextWriter xmlWriter = new XmlTextWriter (stream, System.Text.Encoding.Default);
  370. xmlWriter.Formatting = Formatting.Indented;
  371. Serialize (xmlWriter, o, namespaces);
  372. xmlWriter.WriteEndDocument();
  373. xmlWriter.Flush();
  374. }
  375. public void Serialize (TextWriter textWriter, object o, XmlSerializerNamespaces namespaces)
  376. {
  377. XmlTextWriter xmlWriter = new XmlTextWriter (textWriter);
  378. xmlWriter.Formatting = Formatting.Indented;
  379. Serialize (xmlWriter, o, namespaces);
  380. xmlWriter.WriteEndDocument();
  381. xmlWriter.Flush();
  382. }
  383. public void Serialize (XmlWriter writer, object o, XmlSerializerNamespaces namespaces)
  384. {
  385. Type objType = xsertype;//o.GetType ();
  386. if (IsInbuiltType(objType))
  387. {
  388. if (writer.WriteState == WriteState.Start)
  389. writer.WriteStartDocument ();
  390. SerializeBuiltIn (writer, o);
  391. // Keep WriteState.Content state.
  392. // writer.WriteEndDocument();
  393. writer.Flush ();
  394. return;
  395. }
  396. string rootName = objType.Name;
  397. string rootNs = String.Empty;
  398. string rootPrefix = String.Empty;
  399. if (namespaces == null)
  400. namespaces = new XmlSerializerNamespaces ();
  401. if (namespaces.Count == 0) {
  402. namespaces.Add ("xsd", XmlSchema.Namespace);
  403. namespaces.Add ("xsi", XmlSchema.InstanceNamespace);
  404. }
  405. XmlSerializerNamespaces nss = new XmlSerializerNamespaces ();
  406. XmlQualifiedName[] qnames;
  407. if (writer.WriteState == WriteState.Start)
  408. writer.WriteStartDocument ();
  409. object [] memberObj = (object []) typeTable [objType];
  410. if (memberObj == null)
  411. throw new Exception ("Unknown Type " + objType +
  412. " encountered during Serialization");
  413. Hashtable memberTable = (Hashtable) memberObj [0];
  414. XmlAttributes xmlAttributes = (XmlAttributes) memberTable [""];
  415. //If we have been passed an XmlRoot, set it on the base class
  416. if (rootAttribute != null)
  417. xmlAttributes.XmlRoot = rootAttribute;
  418. if (xmlAttributes.XmlRoot != null) {
  419. isNullable = xmlAttributes.XmlRoot.IsNullable;
  420. if (xmlAttributes.XmlRoot.ElementName != null)
  421. rootName = xmlAttributes.XmlRoot.ElementName;
  422. rootNs = xmlAttributes.XmlRoot.Namespace;
  423. }
  424. if (namespaces != null && namespaces.GetPrefix (rootNs) != null)
  425. rootPrefix = namespaces.GetPrefix (rootNs);
  426. //XMLNS attributes in the Root
  427. XmlAttributes XnsAttrs = (XmlAttributes) ((object[]) typeTable[objType])[1];
  428. if (XnsAttrs != null) {
  429. MemberInfo member = XnsAttrs.MemberInfo;
  430. FieldInfo fieldInfo = member as FieldInfo;
  431. PropertyInfo propertyInfo = member as PropertyInfo;
  432. XmlSerializerNamespaces xns;
  433. if (fieldInfo != null)
  434. xns = (XmlSerializerNamespaces) fieldInfo.GetValue (o);
  435. else
  436. xns = (XmlSerializerNamespaces) propertyInfo.GetValue (o, null);
  437. qnames = xns.ToArray ();
  438. foreach (XmlQualifiedName qname in qnames)
  439. nss.Add (qname.Name, qname.Namespace);
  440. }
  441. //XmlNs from the namespaces passed
  442. qnames = namespaces.ToArray ();
  443. foreach (XmlQualifiedName qname in qnames) {
  444. if (writer.LookupPrefix (qname.Namespace) != qname.Name)
  445. nss.Add (qname.Name, qname.Namespace);
  446. }
  447. writer.WriteStartElement (rootPrefix, rootName, rootNs);
  448. qnames = nss.ToArray();
  449. foreach (XmlQualifiedName qname in qnames) {
  450. if (writer.LookupPrefix (qname.Namespace) != qname.Name)
  451. writer.WriteAttributeString ("xmlns", qname.Name, null, qname.Namespace);
  452. }
  453. if (rootPrefix == String.Empty && rootNs != String.Empty && rootNs != null)
  454. writer.WriteAttributeString (String.Empty, "xmlns", null, rootNs);
  455. SerializeMembers (writer, o, true);//, namespaces);
  456. // Keep WriteState.Content state.
  457. // writer.WriteEndDocument ();
  458. writer.Flush ();
  459. }
  460. private void SerializeBuiltIn (XmlWriter writer, object o)
  461. {
  462. if (o is XmlNode) {
  463. XmlNode n = (XmlNode) o;
  464. XmlNodeReader nrdr = new XmlNodeReader (n);
  465. nrdr.Read ();
  466. if (nrdr.NodeType == XmlNodeType.XmlDeclaration)
  467. nrdr.Read ();
  468. do {
  469. writer.WriteNode (nrdr, false);
  470. } while (nrdr.Read ());
  471. }
  472. else {
  473. TypeData td = TypeTranslator.GetTypeData (o.GetType ());
  474. writer.WriteStartElement (td.ElementName);
  475. WriteBuiltinValue(writer,o);
  476. writer.WriteEndElement();
  477. }
  478. }
  479. private void WriteNilAttribute(XmlWriter writer)
  480. {
  481. writer.WriteAttributeString("nil",XmlSchema.InstanceNamespace, "true");
  482. }
  483. private void WriteBuiltinValue(XmlWriter writer, object o)
  484. {
  485. if(o == null)
  486. WriteNilAttribute(writer);
  487. else
  488. writer.WriteString (GetXmlValue(o));
  489. }
  490. private void SerializeMembers (XmlWriter writer, object o, bool isRoot)
  491. {
  492. if(o == null)
  493. {
  494. WriteNilAttribute(writer);
  495. return;
  496. }
  497. Type objType = o.GetType ();
  498. if (IsInbuiltType(objType))
  499. {
  500. SerializeBuiltIn (writer, o);
  501. return;
  502. }
  503. XmlAttributes nsAttributes = (XmlAttributes) ((object[]) typeTable [objType])[1];
  504. ArrayList attributes = (ArrayList) ((object[]) typeTable [objType])[2];
  505. ArrayList elements = (ArrayList) ((object[]) typeTable [objType])[3];
  506. if (!isRoot && nsAttributes != null) {
  507. MemberInfo member = nsAttributes.MemberInfo;
  508. FieldInfo fieldInfo = member as FieldInfo;
  509. PropertyInfo propertyInfo = member as PropertyInfo;
  510. XmlSerializerNamespaces xns;
  511. if (fieldInfo != null)
  512. xns = (XmlSerializerNamespaces) fieldInfo.GetValue (o);
  513. else
  514. xns = (XmlSerializerNamespaces) propertyInfo.GetValue (o, null);
  515. XmlQualifiedName[] qnames = xns.ToArray ();
  516. foreach (XmlQualifiedName qname in qnames)
  517. if (writer.LookupPrefix (qname.Namespace) != qname.Name)
  518. writer.WriteAttributeString ("xmlns", qname.Name, null, qname.Namespace);
  519. }
  520. //Serialize the Attributes.
  521. foreach (XmlAttributes xmlAttributes in attributes) {
  522. MemberInfo member = xmlAttributes.MemberInfo;
  523. FieldInfo fieldInfo = member as FieldInfo;
  524. PropertyInfo propertyInfo = member as PropertyInfo;
  525. Type attributeType;
  526. object attributeValue;
  527. string attributeValueString;
  528. string attributeName;
  529. string attributeNs;
  530. if (fieldInfo != null) {
  531. attributeType = fieldInfo.FieldType;
  532. attributeValue = fieldInfo.GetValue (o);
  533. }
  534. else {
  535. attributeType = propertyInfo.PropertyType;
  536. attributeValue = propertyInfo.GetValue (o, null);
  537. }
  538. attributeName = xmlAttributes.GetAttributeName (attributeType, member.Name);
  539. attributeNs = xmlAttributes.GetAttributeNamespace (attributeType);
  540. if (attributeValue is XmlQualifiedName) {
  541. XmlQualifiedName qname = (XmlQualifiedName) attributeValue;
  542. if (qname.IsEmpty)
  543. continue;
  544. writer.WriteStartAttribute (attributeName, attributeNs);
  545. writer.WriteQualifiedName (qname.Name, qname.Namespace);
  546. writer.WriteEndAttribute ();
  547. continue;
  548. }
  549. else if (attributeValue is XmlQualifiedName[]) {
  550. XmlQualifiedName[] qnames = (XmlQualifiedName[]) attributeValue;
  551. writer.WriteStartAttribute (attributeName, attributeNs);
  552. int count = 0;
  553. foreach (XmlQualifiedName qname in qnames) {
  554. if (qname.IsEmpty)
  555. continue;
  556. if (count++ > 0)
  557. writer.WriteWhitespace (" ");
  558. writer.WriteQualifiedName (qname.Name, qname.Namespace);
  559. }
  560. writer.WriteEndAttribute ();
  561. continue;
  562. }
  563. else if (attributeValue is XmlAttribute[]) {
  564. XmlAttribute[] xmlattrs = (XmlAttribute[]) attributeValue;
  565. foreach (XmlAttribute xmlattr in xmlattrs) {
  566. xmlattr.WriteTo(writer);
  567. }
  568. continue;
  569. }
  570. attributeValueString = GetXmlValue (attributeValue);
  571. if (attributeValueString != GetXmlValue (xmlAttributes.XmlDefaultValue))
  572. writer.WriteAttributeString (attributeName, attributeNs, attributeValueString);
  573. }
  574. // Serialize Elements
  575. foreach (XmlAttributes xmlElements in elements) {
  576. MemberInfo member = xmlElements.MemberInfo;
  577. FieldInfo fieldInfo = member as FieldInfo;
  578. PropertyInfo propertyInfo = member as PropertyInfo;
  579. Type elementType;
  580. object elementValue;
  581. string elementName;
  582. string elementNs;
  583. if (fieldInfo != null) {
  584. elementType = fieldInfo.FieldType;
  585. elementValue = fieldInfo.GetValue (o);
  586. }
  587. else {
  588. elementType = propertyInfo.PropertyType;
  589. elementValue = propertyInfo.GetValue (o, null);
  590. }
  591. elementName = xmlElements.GetElementName (elementType, member.Name);
  592. elementNs = xmlElements.GetElementNamespace (elementType);
  593. WriteElement (writer, xmlElements, elementName, elementNs, elementType, elementValue);
  594. }
  595. }
  596. [MonoTODO ("Remove FIXMEs")]
  597. private void WriteElement (XmlWriter writer, XmlAttributes attrs, string name, string ns, Type type, Object value)
  598. {
  599. //IF the element has XmlText Attribute, the name of the member is not serialized;
  600. if (attrs.XmlText != null && value != null)
  601. {
  602. if (type == typeof (object[]))
  603. {
  604. foreach(object obj in (object[]) value)
  605. writer.WriteRaw(""+obj);
  606. }
  607. else if (type == typeof (string[]))
  608. {
  609. foreach(string str in (string[]) value)
  610. writer.WriteRaw(str);
  611. }
  612. else if (type == typeof (XmlNode))
  613. {
  614. ((XmlNode) value).WriteTo (writer);
  615. }
  616. else if (type == typeof (XmlNode[]))
  617. {
  618. XmlNode[] nodes = (XmlNode[]) value;
  619. foreach (XmlNode node in nodes)
  620. node.WriteTo (writer);
  621. }
  622. return;
  623. }
  624. //If not text, serialize as an element
  625. //Start the element tag
  626. writer.WriteStartElement (name, ns);
  627. if (IsInbuiltType (type))
  628. {
  629. WriteBuiltinValue(writer,value);
  630. }
  631. else if (type.IsArray && value != null)
  632. {
  633. SerializeArray (writer, value);
  634. }
  635. else if (value is ICollection)
  636. {
  637. BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
  638. //Find a non indexer Count Property with return type of int
  639. PropertyInfo countInfo = type.GetProperty ("Count", flags, null, typeof (int), new Type[0], null);
  640. PropertyInfo itemInfo = type.GetProperty ("Item", flags, null, null, new Type[1] {typeof (int)}, null);
  641. int count = (int) countInfo.GetValue (value, null);
  642. if (count > 0)
  643. for (int i = 0; i < count; i++)
  644. {
  645. object itemValue = itemInfo.GetValue (value, new object[1] {i});
  646. Type itemType = itemInfo.PropertyType;
  647. if (itemValue != null)
  648. {
  649. string itemName = attrs.GetElementName (itemValue.GetType (), TypeTranslator.GetTypeData(itemType).ElementName);
  650. string itemNs = attrs.GetElementNamespace (itemValue.GetType ());
  651. writer.WriteStartElement (itemName, itemNs);
  652. SerializeMembers (writer, itemValue, false);
  653. writer.WriteEndElement ();
  654. }
  655. }
  656. }
  657. else if (value is IEnumerable)
  658. {
  659. // FIXME
  660. }
  661. else if (type.IsEnum)
  662. {
  663. writer.WriteString(GetXmlValue(value));
  664. }
  665. else
  666. { //Complex Type
  667. SerializeMembers (writer, value, false);
  668. }
  669. // Close the Element
  670. writer.WriteEndElement();
  671. }
  672. //Does not take care of any array specific Xml Attributes
  673. [MonoTODO]
  674. private void SerializeArray (XmlWriter writer, object o)
  675. {
  676. Array arr = (o as Array);
  677. if(arr == null || arr.Rank != 1)
  678. throw new ApplicationException("Expected a single dimension Array, Got "+ o);
  679. Type arrayType = arr.GetType().GetElementType();
  680. string arrayTypeName = TypeTranslator.GetTypeData(arrayType).ElementName;
  681. TypeData td = TypeTranslator.GetTypeData (arrayType);
  682. // Special Treatment for Byte array
  683. if(arrayType.Equals(typeof(byte)))
  684. {
  685. WriteBuiltinValue(writer,o);
  686. }
  687. else
  688. {
  689. for(int i=0; i< arr.Length; i++)
  690. {
  691. writer.WriteStartElement (td.ElementName);
  692. object value = arr.GetValue(i);
  693. if (IsInbuiltType (arrayType))
  694. {
  695. WriteBuiltinValue(writer, value);
  696. }
  697. else
  698. {
  699. SerializeMembers(writer, value, false);
  700. }
  701. writer.WriteEndElement();
  702. }
  703. }
  704. }
  705. /// <summary>
  706. /// If the type is a string, valuetype or primitive type we do not populate the TypeTable.
  707. /// If the type is an array, we populate the TypeTable with Element type of the array.
  708. /// If the type implements ICollection, it is handled differently. We do not care for its members.
  709. /// If the type implements IEnumberable, we check that it implements Add(). Don't care for members.
  710. /// </summary>
  711. [MonoTODO ("Remove FIXMEs")]
  712. private void FillTypeTable (Type type)
  713. {
  714. // If it's already in the table, don't add it again.
  715. if (typeTable.Contains (type))
  716. return;
  717. //For value types and strings we don't need the members.
  718. //FIXME: We will need the enum types probably.
  719. if (IsInbuiltType (type))
  720. return;
  721. //Array, ICollection and IEnumberable are treated differenty
  722. if (type.IsArray) {
  723. FillArrayType (type);
  724. return;
  725. }
  726. else if (type.IsEnum) {
  727. FillEnum (type);
  728. return;
  729. }
  730. else {
  731. //There must be a public constructor
  732. //if (!HasDefaultConstructor (type))
  733. //throw new Exception ("Can't Serialize Type " + type.Name + " since it does not have default Constructor");
  734. if (type.GetInterface ("ICollection") == typeof (System.Collections.ICollection)) {
  735. FillICollectionType (type);
  736. return;
  737. }
  738. // if (type.GetInterface ("IDictionary") == typeof (System.Collections.IDictionary)) {
  739. // throw new Exception ("Can't Serialize Type " + type.Name + " since it implements IDictionary");
  740. // }
  741. if (type.GetInterface ("IEnumerable") == typeof (System.Collections.IEnumerable)) {
  742. //FillIEnumerableType(type);
  743. //return;
  744. }
  745. }
  746. //Add the Class to the hashtable.
  747. //Each value of the hashtable has two objects, one is the hashtable with key of membername (for deserialization)
  748. //Other is an Array of XmlSerializernames, Array of XmlAttributes & Array of XmlElements.
  749. Object[] memberObj = new Object[4];
  750. typeTable.Add (type,memberObj);
  751. Hashtable memberTable = new Hashtable ();
  752. memberObj[0] = memberTable;
  753. memberTable.Add ("", XmlAttributes.FromClass (type));
  754. memberObj[1] = null;
  755. ArrayList attributes = new ArrayList ();
  756. memberObj[2] = attributes;
  757. ArrayList elements = new ArrayList ();
  758. memberObj[3] = elements;
  759. //Get the graph of the members. Graph is nothing but the order
  760. //in which MS implementation serializes the members.
  761. MemberInfo[] minfo = GetGraph (type);
  762. foreach (MemberInfo member in minfo) {
  763. FieldInfo fieldInfo = (member as FieldInfo);
  764. PropertyInfo propertyInfo = (member as PropertyInfo);
  765. if (memberTable [member.Name] != null)
  766. continue;
  767. if (fieldInfo != null) {
  768. //If field is readOnly or const, do not serialize it.
  769. if (fieldInfo.IsLiteral || fieldInfo.IsInitOnly)
  770. continue;
  771. XmlAttributes xmlAttributes = XmlAttributes.FromField (member, fieldInfo);
  772. //If XmlAttributes have XmlIgnore, ignore this member
  773. if (xmlAttributes.XmlIgnore)
  774. continue;
  775. //If this member is a XmlNs type, set the XmlNs object.
  776. if (xmlAttributes.Xmlns) {
  777. memberObj[1] = xmlAttributes;
  778. continue;
  779. }
  780. //If the member is a attribute Type, Add to attribute list
  781. if (xmlAttributes.isAttribute)
  782. attributes.Add (xmlAttributes);
  783. else //Add to elements
  784. elements.Add (xmlAttributes);
  785. //Add in the Hashtable.
  786. memberTable.Add (member.Name, xmlAttributes);
  787. if (xmlAttributes.XmlAnyAttribute != null || xmlAttributes.XmlText != null)
  788. continue;
  789. if (xmlAttributes.XmlElements.Count > 0) {
  790. foreach (XmlElementAttribute elem in xmlAttributes.XmlElements) {
  791. if (elem.Type != null)
  792. FillTypeTable (elem.Type);
  793. else
  794. FillTypeTable (fieldInfo.FieldType);
  795. }
  796. continue;
  797. }
  798. if (!IsInbuiltType (fieldInfo.FieldType))
  799. FillTypeTable (fieldInfo.FieldType);
  800. }
  801. else if (propertyInfo != null) {
  802. //If property is readonly or writeonly, do not serialize it.
  803. //Exceptions are properties whose return type is array, ICollection or IEnumerable
  804. //Indexers are not serialized unless the class Implements ICollection.
  805. if (!(propertyInfo.PropertyType.IsArray ||
  806. Implements (propertyInfo.PropertyType, typeof (ICollection)) ||
  807. (propertyInfo.PropertyType != typeof (string) &&
  808. Implements (propertyInfo.PropertyType, typeof (IEnumerable)))))
  809. {
  810. if(!(propertyInfo.CanRead && propertyInfo.CanWrite) || propertyInfo.GetIndexParameters ().Length != 0)
  811. continue;
  812. }
  813. XmlAttributes xmlAttributes = XmlAttributes.FromProperty (member, propertyInfo);
  814. // If XmlAttributes have XmlIgnore, ignore this member
  815. if (xmlAttributes.XmlIgnore)
  816. continue;
  817. // If this member is a XmlNs type, set the XmlNs object.
  818. if (xmlAttributes.Xmlns) {
  819. memberObj[1] = xmlAttributes;
  820. continue;
  821. }
  822. // If the member is a attribute Type, Add to attribute list
  823. if (xmlAttributes.isAttribute)
  824. attributes.Add (xmlAttributes);
  825. else //Add to elements
  826. elements.Add (xmlAttributes);
  827. // OtherWise add in the Hashtable.
  828. memberTable.Add (member.Name, xmlAttributes);
  829. if (xmlAttributes.XmlAnyAttribute != null || xmlAttributes.XmlText != null)
  830. continue;
  831. if (xmlAttributes.XmlElements.Count > 0) {
  832. foreach (XmlElementAttribute elem in xmlAttributes.XmlElements) {
  833. if (elem.Type != null)
  834. FillTypeTable (elem.Type);
  835. else
  836. FillTypeTable (propertyInfo.PropertyType);
  837. }
  838. continue;
  839. }
  840. if (!IsInbuiltType (propertyInfo.PropertyType))
  841. FillTypeTable (propertyInfo.PropertyType);
  842. }
  843. }
  844. // Sort the attributes for the members according to their Order
  845. // This is an extension to MS's Implementation and will be useful
  846. // if our reflection does not return the same order of elements
  847. // as MS .NET impl
  848. if (useOrder)
  849. BubbleSort (elements, XmlAttributes.attrComparer);
  850. }
  851. private void FillArrayType (Type type)
  852. {
  853. if (type.GetArrayRank () != 1)
  854. throw new Exception ("MultiDimensional Arrays are not Supported");
  855. Type arrayType = type.GetElementType ();
  856. if (arrayType.IsArray)
  857. FillArrayType (arrayType);
  858. else if (!IsInbuiltType (arrayType))
  859. FillTypeTable (arrayType);
  860. }
  861. private void FillICollectionType (Type type)
  862. {
  863. //Must have an public Indexer that takes an integer and
  864. //a public Count Property which returns an int.
  865. BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
  866. //Find a non indexer Count Property with return type of int
  867. PropertyInfo countProp = type.GetProperty ("Count", flags, null, typeof (int), new Type[0], null);
  868. if (countProp == null || !countProp.CanRead)
  869. throw new Exception ("Cannot Serialize " + type + " because it implements ICollectoion, but does not implement public Count property");
  870. //Find a indexer Item Property which takes an int
  871. PropertyInfo itemProp = type.GetProperty ("Item", flags, null, null, new Type[1] {typeof (int)}, null);
  872. if (itemProp == null || !itemProp.CanRead || !itemProp.CanWrite)
  873. throw new Exception ("Cannot Serialize " + type + " because it does not have a read/write indexer property that takes an int as argument");
  874. FillTypeTable (itemProp.PropertyType);
  875. }
  876. [MonoTODO]
  877. private void FillIEnumerableType (Type type)
  878. {
  879. //Must implement a public Add method that takes a single parameter.
  880. //The Add method's parameter must be of the same type as is returned from
  881. //the Current property on the value returned from GetEnumerator, or one of that type's bases.
  882. // We currently ignore enumerable types anyway, so this method was junked.
  883. // The code did not do what the documentation above says (if that is even possible!)
  884. return;
  885. }
  886. private void FillEnum (Type type)
  887. {
  888. Hashtable memberTable = new Hashtable ();
  889. BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
  890. typeTable.Add (type, memberTable);
  891. string[] names = Enum.GetNames (type);
  892. foreach (string name in names) {
  893. MemberInfo[] members = type.GetMember (name);
  894. if (members.Length != 1)
  895. throw new Exception("Should never happen. Enum member not present or more than one. " + name);
  896. XmlAttributes xmlAttributes = new XmlAttributes (members[0]);
  897. if (xmlAttributes.XmlIgnore)
  898. continue;
  899. if (xmlAttributes.XmlEnum != null)
  900. memberTable.Add (members[0].Name, xmlAttributes.XmlEnum.Name);
  901. else
  902. memberTable.Add (members[0].Name, members[0].Name);
  903. }
  904. }
  905. private bool HasDefaultConstructor (Type type)
  906. {
  907. ConstructorInfo defaultConstructor = type.GetConstructor (new Type[0]);
  908. if (defaultConstructor == null || defaultConstructor.IsAbstract || defaultConstructor.IsStatic || !defaultConstructor.IsPublic)
  909. return false;
  910. return true;
  911. }
  912. private bool IsInbuiltType (Type type)
  913. {
  914. if (type.IsEnum)
  915. return false;
  916. if (/* type.IsValueType || */type == typeof (string) || type.IsPrimitive)
  917. return true;
  918. if (type == typeof (DateTime) ||
  919. type == typeof (Guid) ||
  920. type == typeof (XmlNode) ||
  921. type.IsSubclassOf (typeof (XmlNode)))
  922. return true;
  923. return false;
  924. }
  925. private static MemberInfo[] GetGraph(Type type)
  926. {
  927. ArrayList typeGraph = new ArrayList ();
  928. GetGraph (type, typeGraph);
  929. return (MemberInfo[]) typeGraph.ToArray (typeof (MemberInfo));
  930. }
  931. private static void GetGraph (Type type, ArrayList typeGraph)
  932. {
  933. BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly;
  934. if (type.BaseType == null)
  935. return;
  936. GetGraph (type.BaseType, typeGraph);
  937. typeGraph.AddRange (type.GetFields (flags));
  938. typeGraph.AddRange (type.GetProperties (flags));
  939. }
  940. private string GetXmlValue (object value)
  941. {
  942. if (value == null)
  943. return null;
  944. #region enum type
  945. if (value is Enum)
  946. {
  947. Type type = value.GetType ();
  948. if (typeTable.ContainsKey (type)) {
  949. Hashtable memberTable = (Hashtable) (typeTable[type]);
  950. if (type.IsDefined (typeof (FlagsAttribute), false)) {
  951. //If value is exactly a single enum member
  952. if (memberTable.Contains (value.ToString ()))
  953. return (string) memberTable[value.ToString ()];
  954. string retval = "";
  955. int enumval = (int) value;
  956. string[] names = Enum.GetNames (type);
  957. foreach (string key in names) {
  958. if (!memberTable.ContainsKey (key))
  959. continue;
  960. //Otherwise multiple values.
  961. int val = (int) Enum.Parse (type, key);
  962. if (val != 0 && (enumval & val) == val)
  963. retval += " " + (string) memberTable[Enum.GetName (type, val)];
  964. }
  965. retval = retval.Trim ();
  966. if (retval.Length == 0)
  967. return null;
  968. return retval;
  969. }
  970. else if (memberTable.ContainsKey (value.ToString ()))
  971. return (string) memberTable[value.ToString()];
  972. else
  973. return null;
  974. }
  975. else
  976. throw new Exception ("Unknown Enumeration");
  977. }
  978. #endregion
  979. if (value is byte[])
  980. return XmlCustomFormatter.FromByteArrayBase64((byte[])value);
  981. if (value is Guid)
  982. return XmlConvert.ToString((Guid)value);
  983. if(value is DateTime)
  984. return XmlConvert.ToString((DateTime)value);
  985. if(value is TimeSpan)
  986. return XmlConvert.ToString((TimeSpan)value);
  987. if(value is bool)
  988. return XmlConvert.ToString((bool)value);
  989. if(value is byte)
  990. return XmlConvert.ToString((byte)value);
  991. if(value is char)
  992. return XmlCustomFormatter.FromChar((char)value);
  993. if(value is decimal)
  994. return XmlConvert.ToString((decimal)value);
  995. if(value is double)
  996. return XmlConvert.ToString((double)value);
  997. if(value is short)
  998. return XmlConvert.ToString((short)value);
  999. if(value is int)
  1000. return XmlConvert.ToString((int)value);
  1001. if(value is long)
  1002. return XmlConvert.ToString((long)value);
  1003. if(value is sbyte)
  1004. return XmlConvert.ToString((sbyte)value);
  1005. if(value is float)
  1006. return XmlConvert.ToString((float)value);
  1007. if(value is ushort)
  1008. return XmlConvert.ToString((ushort)value);
  1009. if(value is uint)
  1010. return XmlConvert.ToString((uint)value);
  1011. if(value is ulong)
  1012. return XmlConvert.ToString((ulong)value);
  1013. if (value is XmlQualifiedName) {
  1014. if (((XmlQualifiedName) value).IsEmpty)
  1015. return null;
  1016. }
  1017. return (value == null) ? null : value.ToString ();
  1018. }
  1019. [MonoTODO ("Remove FIXMEs")]
  1020. private static void ProcessAttributes (XmlAttributes attrs, Hashtable memberTable)
  1021. {
  1022. if (attrs.XmlAnyAttribute != null) {
  1023. // FIXME
  1024. }
  1025. foreach (XmlAnyElementAttribute anyelem in attrs.XmlAnyElements)
  1026. memberTable.Add (new XmlQualifiedName (anyelem.Name, anyelem.Namespace), attrs);
  1027. if (attrs.XmlArray != null) {
  1028. // FIXME
  1029. }
  1030. foreach (XmlArrayItemAttribute item in attrs.XmlArrayItems)
  1031. memberTable.Add (new XmlQualifiedName (item.ElementName, item.Namespace), attrs);
  1032. if (attrs.XmlAttribute != null)
  1033. memberTable.Add (new XmlQualifiedName (attrs.XmlAttribute.AttributeName,attrs.XmlAttribute.Namespace), attrs);
  1034. if (attrs.XmlChoiceIdentifier != null) {
  1035. // FIXME
  1036. }
  1037. foreach (XmlElementAttribute elem in attrs.XmlElements)
  1038. memberTable.Add (new XmlQualifiedName (elem.ElementName, elem.Namespace), attrs);
  1039. if (attrs.XmlEnum != null) {
  1040. // FIXME
  1041. }
  1042. if (attrs.XmlType != null)
  1043. memberTable.Add (new XmlQualifiedName (attrs.XmlType.TypeName, attrs.XmlType.Namespace), attrs);
  1044. }
  1045. private bool Implements (Type type, Type interfaceType)
  1046. {
  1047. return (type.GetInterface (interfaceType.Name) == interfaceType);
  1048. }
  1049. private static void BubbleSort (ArrayList array, IComparer comparer)
  1050. {
  1051. int len = array.Count;
  1052. object obj1, obj2;
  1053. for (int i=0; i < len; i++) {
  1054. for (int j=0; j < len -i -1; j++) {
  1055. obj1 = array[j];
  1056. obj2 = array[j+1];
  1057. if (comparer.Compare (obj2 , obj1 ) < 0) {
  1058. array[j] = obj2;
  1059. array[j+1] = obj1;
  1060. }
  1061. }
  1062. }
  1063. }
  1064. #endregion // Methods
  1065. }
  1066. }