XmlSerializer.cs 35 KB

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