473,394 Members | 1,841 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

XML Serialization of complex types as XML attributes

Hi all

..NET Framework 1.1

I have created several types that are serailized to XML as strings. Someting
like this:

public struct MyInt32 : IXmlSerializable
{
int value;

public MyInt32(int value)
{
this.value = value;
}

public static implicit operator Int32(MyInt32 value)
{
return value.value;
}

public static implicit operator MyInt32(Int32 value)
{
return new MyInt32(value);
}

public static MyInt32 Parse(string str)
{
return int.Parse(str);
}

public static bool TryParse(string str, out MyInt32 value)
{
try
{
value = int.Parse(str);
return true;
}
catch
{
value = 0;
return false;
}
}

XmlSchema IXmlSerializable.GetSchema()
{
return null;
}

void IXmlSerializable.WriteXml(XmlWriter writer)
{
writer.WriteString(XmlConvert.ToString(this.value) );
}

void IXmlSerializable.ReadXml(XmlReader reader)
{
this.value = XmlConvert.ToInt32(reader.ReadString());
}

}

The XML serialization as a XML element works without any problems:

class MyClass
{
[XmlElement("v")]
public MyInt32 myValue;
}

But when I mark myValue with the XmlAttributeAttribute:

class MyClass
{
[XmlAttribute("v")]
public MyInt32 myValue;
}

I get:

System.InvalidOperationException: There was an error reflecting type
'ConsoleApplication.DTO'. ---> System.InvalidOperationException: There was an
error reflecting field 'v'. ---> System.InvalidOperationException: Cannot
serialize member 'v'. XmlAttribute/XmlText cannot be used to encode complex
types.
at
System.Xml.Serialization.XmlReflectionImporter.Imp ortAccessorMapping(MemberMapping
accessor, FieldModel model, XmlAttributes a, String ns, Type
choiceIdentifierType)
at
System.Xml.Serialization.XmlReflectionImporter.Imp ortFieldMapping(StructModel
parent, FieldModel model, XmlAttributes a, String ns)
at
System.Xml.Serialization.XmlReflectionImporter.Imp ortStructLikeMapping(StructModel model, String ns)
--- End of inner exception stack trace ---
at
System.Xml.Serialization.XmlReflectionImporter.Imp ortStructLikeMapping(StructModel model, String ns)
at
System.Xml.Serialization.XmlReflectionImporter.Imp ortTypeMapping(TypeModel
model, String ns, ImportContext context, String dataType, Boolean repeats)
--- End of inner exception stack trace ---
at
System.Xml.Serialization.XmlReflectionImporter.Imp ortTypeMapping(TypeModel
model, String ns, ImportContext context, String dataType, Boolean repeats)
at System.Xml.Serialization.XmlReflectionImporter.Imp ortElement(TypeModel
model, XmlRootAttribute root, String defaultNamespace)
at System.Xml.Serialization.XmlReflectionImporter.Imp ortTypeMapping(Type
type, XmlRootAttribute root, String defaultNamespace)
at System.Xml.Serialization.XmlReflectionImporter.Imp ortTypeMapping(Type
type)
at System.Xml.Serialization.XmlSerializer..ctor(Type type, String
defaultNamespace)
at System.Xml.Serialization.XmlSerializer..ctor(Type type)
at ConsoleApplication.Program.Main()

How can I serialize MyType as a XML attribute?

--
Paulo Morgado

Jan 23 '06 #1
3 14952
The XmlSerializer doesn't know that your IXmlSerializable just calls
WriteString. What if you called WriteElementString instead? So the right
way to do this is expose a string Property

[XmlIgnore]
public MyInt32 MyValue;

[XmlAttribute("v")]
public string myValue {
get { return MyValue.ToString(); }
set { MyValue = MyInt32.Parse(value); }
}

"Paulo Morgado [MVP]" <pa***********@community.nospam> wrote in message
news:69**********************************@microsof t.com...
Hi all

.NET Framework 1.1

I have created several types that are serailized to XML as strings.
Someting
like this:

public struct MyInt32 : IXmlSerializable
{
int value;

public MyInt32(int value)
{
this.value = value;
}

public static implicit operator Int32(MyInt32 value)
{
return value.value;
}

public static implicit operator MyInt32(Int32 value)
{
return new MyInt32(value);
}

public static MyInt32 Parse(string str)
{
return int.Parse(str);
}

public static bool TryParse(string str, out MyInt32 value)
{
try
{
value = int.Parse(str);
return true;
}
catch
{
value = 0;
return false;
}
}

XmlSchema IXmlSerializable.GetSchema()
{
return null;
}

void IXmlSerializable.WriteXml(XmlWriter writer)
{
writer.WriteString(XmlConvert.ToString(this.value) );
}

void IXmlSerializable.ReadXml(XmlReader reader)
{
this.value = XmlConvert.ToInt32(reader.ReadString());
}

}

The XML serialization as a XML element works without any problems:

class MyClass
{
[XmlElement("v")]
public MyInt32 myValue;
}

But when I mark myValue with the XmlAttributeAttribute:

class MyClass
{
[XmlAttribute("v")]
public MyInt32 myValue;
}

I get:

System.InvalidOperationException: There was an error reflecting type
'ConsoleApplication.DTO'. ---> System.InvalidOperationException: There was
an
error reflecting field 'v'. ---> System.InvalidOperationException: Cannot
serialize member 'v'. XmlAttribute/XmlText cannot be used to encode
complex
types.
at
System.Xml.Serialization.XmlReflectionImporter.Imp ortAccessorMapping(MemberMapping
accessor, FieldModel model, XmlAttributes a, String ns, Type
choiceIdentifierType)
at
System.Xml.Serialization.XmlReflectionImporter.Imp ortFieldMapping(StructModel
parent, FieldModel model, XmlAttributes a, String ns)
at
System.Xml.Serialization.XmlReflectionImporter.Imp ortStructLikeMapping(StructModel
model, String ns)
--- End of inner exception stack trace ---
at
System.Xml.Serialization.XmlReflectionImporter.Imp ortStructLikeMapping(StructModel
model, String ns)
at
System.Xml.Serialization.XmlReflectionImporter.Imp ortTypeMapping(TypeModel
model, String ns, ImportContext context, String dataType, Boolean repeats)
--- End of inner exception stack trace ---
at
System.Xml.Serialization.XmlReflectionImporter.Imp ortTypeMapping(TypeModel
model, String ns, ImportContext context, String dataType, Boolean repeats)
at
System.Xml.Serialization.XmlReflectionImporter.Imp ortElement(TypeModel
model, XmlRootAttribute root, String defaultNamespace)
at System.Xml.Serialization.XmlReflectionImporter.Imp ortTypeMapping(Type
type, XmlRootAttribute root, String defaultNamespace)
at System.Xml.Serialization.XmlReflectionImporter.Imp ortTypeMapping(Type
type)
at System.Xml.Serialization.XmlSerializer..ctor(Type type, String
defaultNamespace)
at System.Xml.Serialization.XmlSerializer..ctor(Type type)
at ConsoleApplication.Program.Main()

How can I serialize MyType as a XML attribute?

--
Paulo Morgado

Jan 24 '06 #2
Hi Chris. Thanks for your reply.

There are two things wrong in your approach to the problem:

1. Parse and ToString, at least in the way you showed, are all about
presentation and are culture dependente. XmlConvert should have been used,
but it's not extensible either.

2. You are not serializing MyValue and you are creating a new property that
I don't want my classes to have. I should have told that I already came to
this conclusion and also added an Obsolete attribute to warn developers not
to use that property.

I can understand that the XmlSerializer doesn't know how i will serialize my
type. There should be a IXmlSerilizableSomething to serialize the type as
just a string and the XmlSerializer should handle it. Another way to do it
would be to let the XmlReader/XmlWriter to handle if proper XML was being
read/written.

--
Paulo Morgado

"Chris Lovett" wrote:
The XmlSerializer doesn't know that your IXmlSerializable just calls
WriteString. What if you called WriteElementString instead? So the right
way to do this is expose a string Property

[XmlIgnore]
public MyInt32 MyValue;

[XmlAttribute("v")]
public string myValue {
get { return MyValue.ToString(); }
set { MyValue = MyInt32.Parse(value); }
}


Jan 24 '06 #3
Hi Chris,

Seems like I dumped my frustration on you. Sorry.

--
Paulo Morgado

Jan 24 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Demetri | last post by:
I have 2 web services. Web service "Main" and a Web Service "Proxy". I also have a shared libary of complex types. The "Proxy" web service simply calles methods of the "Main" web service. When...
5
by: Todd Steury | last post by:
Greetings Python'ers: I'm just an amature who occasionally uses Python for complex mathematical models. The current model I'm working with occasionally generates really large numbers that are...
5
by: HQM | last post by:
If I create an element X of a primitive type with minOccurs=0 and nillable=true and run it through the WSDL generator I get a class with a property "X" of the primitive type plus a boolean...
0
by: Demetri | last post by:
I have 2 web services. Web service "Main" and a Web Service "Proxy". I also have a shared libary of complex types. The "Proxy" web service simply calles methods of the "Main" web service. When...
1
by: jendra | last post by:
I'm new in using visual studio .net 2003 and web services. I found the web reference feature very useful and easy to use for handling web service methods which return simple types. However, i want...
1
by: GAURAV KRISHNA | last post by:
I am able to deserialize an array using XMLSerializer but the size of an array is 0.The problem seems to be because of unqualified element name but I am not very sure. Here is what I did: I...
2
by: Philip Reimer | last post by:
Hello. We have here a Java web service that has been created using Apache Axis 1.4, using the document/literal wrapped style, and returns complex types in its methods. When consuming the web...
0
by: sheepk | last post by:
Hi, I've read this topic in the archives : http://www.thescripts.com/forum/thread626912.html And I've got the same problem using webservices with dot net. I'm trying to get complex types (in...
0
by: Suppi | last post by:
Hi all, we're doing a lot of xml/java (de)serialization and thus have defined a bigger type hierarchy in xml-schema. It starts with basic complex type as base classes. These are extended via...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.