2
0

XmlSerializationWriterInterpreter.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. //
  2. // XmlSerializationWriterInterpreter.cs:
  3. //
  4. // Author:
  5. // Lluis Sanchez Gual ([email protected])
  6. //
  7. // (C) 2002, 2003 Ximian, Inc. http://www.ximian.com
  8. //
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System;
  30. using System.Text;
  31. using System.Collections;
  32. using System.Reflection;
  33. using System.Xml.Schema;
  34. namespace System.Xml.Serialization
  35. {
  36. internal class XmlSerializationWriterInterpreter: XmlSerializationWriter
  37. {
  38. XmlMapping _typeMap;
  39. SerializationFormat _format;
  40. public XmlSerializationWriterInterpreter (XmlMapping typeMap)
  41. {
  42. _typeMap = typeMap;
  43. _format = typeMap.Format;
  44. }
  45. protected override void InitCallbacks ()
  46. {
  47. ArrayList maps = _typeMap.RelatedMaps;
  48. if (maps != null)
  49. {
  50. foreach (XmlTypeMapping map in maps) {
  51. CallbackInfo info = new CallbackInfo (this, map);
  52. if (map.TypeData.SchemaType == SchemaTypes.Enum) AddWriteCallback(map.TypeData.Type, map.XmlType, map.Namespace, new XmlSerializationWriteCallback (info.WriteEnum));
  53. else AddWriteCallback(map.TypeData.Type, map.XmlType, map.Namespace, new XmlSerializationWriteCallback (info.WriteObject));
  54. }
  55. }
  56. }
  57. public void WriteRoot (object ob)
  58. {
  59. WriteStartDocument ();
  60. if (_typeMap is XmlTypeMapping)
  61. {
  62. XmlTypeMapping mp = (XmlTypeMapping) _typeMap;
  63. if (mp.TypeData.SchemaType == SchemaTypes.Class || mp.TypeData.SchemaType == SchemaTypes.Array)
  64. TopLevelElement ();
  65. if (_format == SerializationFormat.Literal)
  66. WriteObject (mp, ob, mp.ElementName, mp.Namespace, true, false, true);
  67. else
  68. WritePotentiallyReferencingElement (mp.ElementName, mp.Namespace, ob, mp.TypeData.Type, true, false);
  69. }
  70. else if (ob is object[])
  71. WriteMessage ((XmlMembersMapping)_typeMap, (object[]) ob);
  72. else
  73. throw CreateUnknownTypeException (ob);
  74. WriteReferencedElements ();
  75. }
  76. protected XmlTypeMapping GetTypeMap (Type type)
  77. {
  78. ArrayList maps = _typeMap.RelatedMaps;
  79. if (maps != null)
  80. {
  81. foreach (XmlTypeMapping map in maps)
  82. if (map.TypeData.Type == type) return map;
  83. }
  84. throw new InvalidOperationException ("Type " + type + " not mapped");
  85. }
  86. protected virtual void WriteObject (XmlTypeMapping typeMap, object ob, string element, string namesp, bool isNullable, bool needType, bool writeWrappingElem)
  87. {
  88. if (ob == null)
  89. {
  90. if (isNullable)
  91. {
  92. if (_format == SerializationFormat.Literal) WriteNullTagLiteral(element, namesp);
  93. else WriteNullTagEncoded (element, namesp);
  94. }
  95. return;
  96. }
  97. if (ob is XmlNode)
  98. {
  99. if (_format == SerializationFormat.Literal) WriteElementLiteral((XmlNode)ob, "", "", true, false);
  100. else WriteElementEncoded((XmlNode)ob, "", "", true, false);
  101. return;
  102. }
  103. if (typeMap.TypeData.SchemaType == SchemaTypes.XmlSerializable)
  104. {
  105. WriteSerializable ((IXmlSerializable)ob, element, namesp, isNullable);
  106. return;
  107. }
  108. XmlTypeMapping map = typeMap.GetRealTypeMap (ob.GetType().FullName);
  109. if (map == null)
  110. {
  111. WriteTypedPrimitive (element, namesp, ob, true);
  112. return;
  113. }
  114. if (writeWrappingElem)
  115. {
  116. if (map != typeMap || _format == SerializationFormat.Encoded) needType = true;
  117. WriteStartElement (element, namesp, ob);
  118. }
  119. if (needType)
  120. WriteXsiType(map.XmlType, map.XmlTypeNamespace);
  121. switch (map.TypeData.SchemaType)
  122. {
  123. case SchemaTypes.Class: WriteObjectElement (map, ob, element, namesp); break;
  124. case SchemaTypes.Array: WriteListElement (map, ob, element, namesp); break;
  125. case SchemaTypes.Primitive: WritePrimitiveElement (map, ob, element, namesp); break;
  126. case SchemaTypes.Enum: WriteEnumElement (map, ob, element, namesp); break;
  127. }
  128. if (writeWrappingElem)
  129. WriteEndElement (ob);
  130. }
  131. protected virtual void WriteMessage (XmlMembersMapping membersMap, object[] parameters)
  132. {
  133. if (membersMap.HasWrapperElement) {
  134. TopLevelElement ();
  135. WriteStartElement(membersMap.ElementName, membersMap.Namespace, (_format == SerializationFormat.Encoded));
  136. if (Writer.LookupPrefix (XmlSchema.Namespace) == null)
  137. WriteAttribute ("xmlns","xsd",XmlSchema.Namespace,XmlSchema.Namespace);
  138. if (Writer.LookupPrefix (XmlSchema.InstanceNamespace) == null)
  139. WriteAttribute ("xmlns","xsi",XmlSchema.InstanceNamespace,XmlSchema.InstanceNamespace);
  140. }
  141. WriteMembers ((ClassMap)membersMap.ObjectMap, parameters, true);
  142. if (membersMap.HasWrapperElement)
  143. WriteEndElement();
  144. }
  145. protected virtual void WriteObjectElement (XmlTypeMapping typeMap, object ob, string element, string namesp)
  146. {
  147. ClassMap map = (ClassMap)typeMap.ObjectMap;
  148. if (map.NamespaceDeclarations != null)
  149. WriteNamespaceDeclarations ((XmlSerializerNamespaces) map.NamespaceDeclarations.GetValue (ob));
  150. WriteObjectElementAttributes (typeMap, ob);
  151. WriteObjectElementElements (typeMap, ob);
  152. }
  153. protected virtual void WriteObjectElementAttributes (XmlTypeMapping typeMap, object ob)
  154. {
  155. ClassMap map = (ClassMap)typeMap.ObjectMap;
  156. WriteAttributeMembers (map, ob, false);
  157. }
  158. protected virtual void WriteObjectElementElements (XmlTypeMapping typeMap, object ob)
  159. {
  160. ClassMap map = (ClassMap)typeMap.ObjectMap;
  161. WriteElementMembers (map, ob, false);
  162. }
  163. void WriteMembers (ClassMap map, object ob, bool isValueList)
  164. {
  165. WriteAttributeMembers (map, ob, isValueList);
  166. WriteElementMembers (map, ob, isValueList);
  167. }
  168. void WriteAttributeMembers (ClassMap map, object ob, bool isValueList)
  169. {
  170. // Write attributes
  171. ICollection attributes = map.AttributeMembers;
  172. if (attributes != null)
  173. {
  174. foreach (XmlTypeMapMemberAttribute attr in attributes) {
  175. if (MemberHasValue (attr, ob, isValueList))
  176. WriteAttribute (attr.AttributeName, attr.Namespace, GetStringValue (attr.MappedType, attr.TypeData, GetMemberValue (attr, ob, isValueList)));
  177. }
  178. }
  179. XmlTypeMapMember anyAttrMember = map.DefaultAnyAttributeMember;
  180. if (anyAttrMember != null && MemberHasValue (anyAttrMember, ob, isValueList))
  181. {
  182. ICollection extraAtts = (ICollection) GetMemberValue (anyAttrMember, ob, isValueList);
  183. if (extraAtts != null)
  184. {
  185. foreach (XmlAttribute attr in extraAtts)
  186. WriteXmlAttribute (attr, ob);
  187. }
  188. }
  189. }
  190. void WriteElementMembers (ClassMap map, object ob, bool isValueList)
  191. {
  192. ICollection members = map.ElementMembers;
  193. if (members != null)
  194. {
  195. foreach (XmlTypeMapMemberElement member in members)
  196. {
  197. if (!MemberHasValue (member, ob, isValueList)) continue;
  198. object memberValue = GetMemberValue (member, ob, isValueList);
  199. Type memType = member.GetType();
  200. if (memType == typeof(XmlTypeMapMemberList))
  201. {
  202. WriteMemberElement ((XmlTypeMapElementInfo) member.ElementInfo[0], memberValue);
  203. }
  204. else if (memType == typeof(XmlTypeMapMemberFlatList))
  205. {
  206. if (memberValue != null)
  207. WriteListContent (member.TypeData, ((XmlTypeMapMemberFlatList)member).ListMap, memberValue, null);
  208. }
  209. else if (memType == typeof(XmlTypeMapMemberAnyElement))
  210. {
  211. if (memberValue != null)
  212. WriteAnyElementContent ((XmlTypeMapMemberAnyElement)member, memberValue);
  213. }
  214. else if (memType == typeof(XmlTypeMapMemberAnyAttribute))
  215. {
  216. // Ignore
  217. }
  218. else if (memType == typeof(XmlTypeMapMemberElement))
  219. {
  220. XmlTypeMapElementInfo elem = member.FindElement (ob, memberValue);
  221. WriteMemberElement (elem, memberValue);
  222. }
  223. else
  224. throw new InvalidOperationException ("Unknown member type");
  225. }
  226. }
  227. }
  228. object GetMemberValue (XmlTypeMapMember member, object ob, bool isValueList)
  229. {
  230. if (isValueList) return ((object[])ob)[member.Index];
  231. else return member.GetValue (ob);
  232. }
  233. bool MemberHasValue (XmlTypeMapMember member, object ob, bool isValueList)
  234. {
  235. if (isValueList) {
  236. return member.Index < ((object[])ob).Length;
  237. }
  238. else if (member.DefaultValue != System.DBNull.Value) {
  239. object val = GetMemberValue (member, ob, isValueList);
  240. if (val == null && member.DefaultValue == null) return false;
  241. if (val != null && val.GetType().IsEnum)
  242. {
  243. if (val.Equals (member.DefaultValue)) return false;
  244. Type t = Enum.GetUnderlyingType(val.GetType());
  245. val = Convert.ChangeType (val, t);
  246. }
  247. if (val != null && val.Equals (member.DefaultValue)) return false;
  248. }
  249. else if (member.IsOptionalValueType)
  250. return member.GetValueSpecified (ob);
  251. return true;
  252. }
  253. void WriteMemberElement (XmlTypeMapElementInfo elem, object memberValue)
  254. {
  255. switch (elem.TypeData.SchemaType)
  256. {
  257. case SchemaTypes.XmlNode:
  258. string elemName = elem.WrappedElement ? elem.ElementName : "";
  259. if (_format == SerializationFormat.Literal) WriteElementLiteral(((XmlNode)memberValue), elemName, elem.Namespace, elem.IsNullable, false);
  260. else WriteElementEncoded(((XmlNode)memberValue), elemName, elem.Namespace, elem.IsNullable, false);
  261. break;
  262. case SchemaTypes.Enum:
  263. case SchemaTypes.Primitive:
  264. if (_format == SerializationFormat.Literal)
  265. WritePrimitiveValueLiteral (memberValue, elem.ElementName, elem.Namespace, elem.MappedType, elem.TypeData, elem.WrappedElement, elem.IsNullable);
  266. else
  267. WritePrimitiveValueEncoded (memberValue, elem.ElementName, elem.Namespace, new XmlQualifiedName (elem.TypeData.XmlType, elem.DataTypeNamespace), elem.MappedType, elem.TypeData, elem.WrappedElement, elem.IsNullable);
  268. break;
  269. case SchemaTypes.Array:
  270. if (memberValue == null) {
  271. if (!elem.IsNullable) return;
  272. if (_format == SerializationFormat.Literal) WriteNullTagLiteral (elem.ElementName, elem.Namespace);
  273. else WriteNullTagEncoded (elem.ElementName, elem.Namespace);
  274. }
  275. else if (elem.MappedType.MultiReferenceType)
  276. WriteReferencingElement (elem.ElementName, elem.Namespace, memberValue, elem.IsNullable);
  277. else {
  278. WriteStartElement(elem.ElementName, elem.Namespace, memberValue);
  279. WriteListContent (elem.TypeData, (ListMap) elem.MappedType.ObjectMap, memberValue, null);
  280. WriteEndElement (memberValue);
  281. }
  282. break;
  283. case SchemaTypes.Class:
  284. if (elem.MappedType.MultiReferenceType) {
  285. if (elem.MappedType.TypeData.Type == typeof(object))
  286. WritePotentiallyReferencingElement (elem.ElementName, elem.Namespace, memberValue, null, false, elem.IsNullable);
  287. else
  288. WriteReferencingElement (elem.ElementName, elem.Namespace, memberValue, elem.IsNullable);
  289. }
  290. else WriteObject (elem.MappedType, memberValue, elem.ElementName, elem.Namespace, elem.IsNullable, false, true);
  291. break;
  292. case SchemaTypes.XmlSerializable:
  293. WriteSerializable ((IXmlSerializable) memberValue, elem.ElementName, elem.Namespace, elem.IsNullable);
  294. break;
  295. default:
  296. throw new NotSupportedException ("Invalid value type");
  297. }
  298. }
  299. void WritePrimitiveValueLiteral (object memberValue, string name, string ns, XmlTypeMapping mappedType, TypeData typeData, bool wrapped, bool isNullable)
  300. {
  301. if (!wrapped) {
  302. WriteValue (GetStringValue (mappedType, typeData, memberValue));
  303. }
  304. else if (isNullable) {
  305. if (typeData.Type == typeof(XmlQualifiedName)) WriteNullableQualifiedNameLiteral (name, ns, (XmlQualifiedName)memberValue);
  306. else WriteNullableStringLiteral (name, ns, GetStringValue (mappedType, typeData, memberValue));
  307. }
  308. else {
  309. if (typeData.Type == typeof(XmlQualifiedName)) WriteElementQualifiedName (name, ns, (XmlQualifiedName)memberValue);
  310. else WriteElementString (name, ns, GetStringValue (mappedType, typeData, memberValue));
  311. }
  312. }
  313. void WritePrimitiveValueEncoded (object memberValue, string name, string ns, XmlQualifiedName xsiType, XmlTypeMapping mappedType, TypeData typeData, bool wrapped, bool isNullable)
  314. {
  315. if (!wrapped) {
  316. WriteValue (GetStringValue (mappedType, typeData, memberValue));
  317. }
  318. else if (isNullable) {
  319. if (typeData.Type == typeof(XmlQualifiedName)) WriteNullableQualifiedNameEncoded (name, ns, (XmlQualifiedName)memberValue, xsiType);
  320. else WriteNullableStringEncoded (name, ns, GetStringValue (mappedType, typeData, memberValue), xsiType);
  321. }
  322. else {
  323. if (typeData.Type == typeof(XmlQualifiedName)) WriteElementQualifiedName (name, ns, (XmlQualifiedName)memberValue, xsiType);
  324. else WriteElementString (name, ns, GetStringValue (mappedType, typeData, memberValue), xsiType);
  325. }
  326. }
  327. protected virtual void WriteListElement (XmlTypeMapping typeMap, object ob, string element, string namesp)
  328. {
  329. if (_format == SerializationFormat.Encoded)
  330. {
  331. string n, ns;
  332. int itemCount = GetListCount (typeMap.TypeData, ob);
  333. ((ListMap) typeMap.ObjectMap).GetArrayType (itemCount, out n, out ns);
  334. string arrayType = (ns != string.Empty) ? FromXmlQualifiedName (new XmlQualifiedName(n,ns)) : n;
  335. WriteAttribute ("arrayType", XmlSerializer.EncodingNamespace, arrayType);
  336. }
  337. WriteListContent (typeMap.TypeData, (ListMap) typeMap.ObjectMap, ob, null);
  338. }
  339. void WriteListContent (TypeData listType, ListMap map, object ob, StringBuilder targetString)
  340. {
  341. if (listType.Type.IsArray)
  342. {
  343. Array array = (Array)ob;
  344. for (int n=0; n<array.Length; n++)
  345. {
  346. object item = array.GetValue (n);
  347. XmlTypeMapElementInfo info = map.FindElement (item);
  348. if (info != null && targetString == null) WriteMemberElement (info, item);
  349. else if (info != null && targetString != null) targetString.Append (GetStringValue (info.MappedType, info.TypeData, item)).Append (" ");
  350. else if (item != null) throw CreateUnknownTypeException (item);
  351. }
  352. }
  353. else if (ob is ICollection)
  354. {
  355. int count = (int) listType.Type.GetProperty ("Count").GetValue(ob,null);
  356. PropertyInfo itemProp = TypeData.GetIndexerProperty (listType.Type);
  357. object[] index = new object[1];
  358. for (int n=0; n<count; n++)
  359. {
  360. index[0] = n;
  361. object item = itemProp.GetValue (ob, index);
  362. XmlTypeMapElementInfo info = map.FindElement (item);
  363. if (info != null && targetString == null) WriteMemberElement (info, item);
  364. else if (info != null && targetString != null) targetString.Append (GetStringValue (info.MappedType, info.TypeData, item)).Append (" ");
  365. else if (item != null) throw CreateUnknownTypeException (item);
  366. }
  367. }
  368. else if (ob is IEnumerable)
  369. {
  370. IEnumerable e = (IEnumerable)ob;
  371. foreach (object item in e)
  372. {
  373. XmlTypeMapElementInfo info = map.FindElement (item);
  374. if (info != null && targetString == null) WriteMemberElement (info, item);
  375. else if (info != null && targetString != null) targetString.Append (GetStringValue (info.MappedType, info.TypeData, item)).Append (" ");
  376. else if (item != null) throw CreateUnknownTypeException (item);
  377. }
  378. }
  379. else
  380. throw new Exception ("Unsupported collection type");
  381. }
  382. int GetListCount (TypeData listType, object ob)
  383. {
  384. if (listType.Type.IsArray)
  385. return ((Array)ob).Length;
  386. else
  387. return (int) listType.Type.GetProperty ("Count").GetValue(ob,null);
  388. }
  389. void WriteAnyElementContent (XmlTypeMapMemberAnyElement member, object memberValue)
  390. {
  391. if (member.TypeData.Type == typeof (XmlElement)) {
  392. memberValue = new object[] { memberValue };
  393. }
  394. bool canBeText = member.CanBeText;
  395. Array elems = (Array) memberValue;
  396. foreach (XmlNode elem in elems)
  397. {
  398. if (elem is XmlElement)
  399. {
  400. if (member.IsElementDefined (elem.Name, elem.NamespaceURI))
  401. {
  402. if (_format == SerializationFormat.Literal) WriteElementLiteral (elem, "", "", false, true);
  403. else WriteElementEncoded (elem, "", "", false, true);
  404. }
  405. else
  406. throw CreateUnknownAnyElementException (elem.Name, elem.NamespaceURI);
  407. }
  408. else if (elem is XmlCharacterData)
  409. elem.WriteTo (Writer);
  410. else
  411. throw CreateUnknownTypeException (elem);
  412. }
  413. }
  414. protected virtual void WritePrimitiveElement (XmlTypeMapping typeMap, object ob, string element, string namesp)
  415. {
  416. Writer.WriteString (GetStringValue (typeMap, typeMap.TypeData, ob));
  417. }
  418. protected virtual void WriteEnumElement (XmlTypeMapping typeMap, object ob, string element, string namesp)
  419. {
  420. Writer.WriteString (GetEnumXmlValue (typeMap, ob));
  421. }
  422. string GetStringValue (XmlTypeMapping typeMap, TypeData type, object value)
  423. {
  424. if (type.SchemaType == SchemaTypes.Array) {
  425. if (value == null) return null;
  426. StringBuilder sb = new StringBuilder ();
  427. WriteListContent (typeMap.TypeData, (ListMap)typeMap.ObjectMap, value, sb);
  428. return sb.ToString ().Trim ();
  429. }
  430. else if (type.SchemaType == SchemaTypes.Enum)
  431. return GetEnumXmlValue (typeMap, value);
  432. else if (type.Type == typeof (XmlQualifiedName))
  433. return FromXmlQualifiedName ((XmlQualifiedName)value);
  434. else if (value == null)
  435. return null;
  436. else
  437. return XmlCustomFormatter.ToXmlString (type, value);
  438. }
  439. string GetEnumXmlValue (XmlTypeMapping typeMap, object ob)
  440. {
  441. EnumMap map = (EnumMap)typeMap.ObjectMap;
  442. return map.GetXmlName (ob);
  443. }
  444. class CallbackInfo
  445. {
  446. XmlSerializationWriterInterpreter _swi;
  447. XmlTypeMapping _typeMap;
  448. public CallbackInfo (XmlSerializationWriterInterpreter swi, XmlTypeMapping typeMap)
  449. {
  450. _swi = swi;
  451. _typeMap = typeMap;
  452. }
  453. internal void WriteObject (object ob)
  454. {
  455. _swi.WriteObject (_typeMap, ob, _typeMap.ElementName, _typeMap.Namespace, false, false, false);
  456. }
  457. internal void WriteEnum (object ob)
  458. {
  459. _swi.WriteObject (_typeMap, ob, _typeMap.ElementName, _typeMap.Namespace, false, true, false);
  460. }
  461. }
  462. }
  463. }