XmlSerializer.cs 36 KB

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