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