473,320 Members | 2,071 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,320 software developers and data experts.

XmlSerializer Empty Element - NULL value

Hi,
I'm using XmlSerializer to create an object from the XML string. I
would like to know whether I can get a null value for an empty XML
element.
Actually the XmlSerializer assigns "" (empty string) for a string
if the corresponding element is missing in the XML.

Input XML:
<DemoClass><A>some value</A><B></B><DemoClass>

Class Structure:
public class DemoClass
{
public string A;
public string B;
}
It creates the object with the proper value for "A" and empty
string B.

Is there any way I can get null for "B" instead of "" (empty
string) ?

Thanks,
Kumar

Nov 2 '06 #1
7 34622
As this little program shows everything works fine in your code.
The only thing that is wrong is your input string for deserialization.

public class MainClass
{
public static void Main(string[] argv) {
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.Xml.Serialization.XmlSerializer ser = new
System.Xml.Serialization.XmlSerializer(typeof(Demo Class));

Console.WriteLine("Not null");
DemoClass demo = new DemoClass();
demo.B = "Not Null";
ser.Serialize(new System.IO.StringWriter(sb), demo);
Console.WriteLine(sb.ToString());
demo = ser.Deserialize(new System.IO.StringReader(sb.ToString()))
as DemoClass;
Console.WriteLine(demo.ToString());
Console.WriteLine();

Console.WriteLine("Null");
sb = new System.Text.StringBuilder();
demo = new DemoClass();
ser.Serialize(new System.IO.StringWriter(sb), demo);
Console.WriteLine(sb.ToString());
demo = ser.Deserialize(new System.IO.StringReader(sb.ToString()))
as DemoClass;
Console.WriteLine(demo.ToString());

Console.Read();
}

public class DemoClass
{
private string a = "Hello, World";
private string b;

public string A {
get { return a; }
set { a = value; }
}

public string B {
get { return b; }
set { b = value; }
}

public override string ToString()
{
return "A = " + a + Environment.NewLine + "B = " + b;
}
}

Nov 2 '06 #2
Actually the XmlSerializer assigns "" (empty string) for a string
if the corresponding element is missing in the XML.
"Missing" is very different to "empty"; your B is empty, not missing.

Anyway, no: it doesn't; first it initialises the class using the field
initialisers and the default ctor. Then it applies all the *found* items,
else applies the [DefaultValue] (if one) to any that were omitted. If it
isn't in the xml it isn't set, so it would remain null. I guess your *real*
class is initialising it to "", or the data is in the xml.

If you really want to turn an *included* (blank) <B></Bto a null, then:

If *all* "" values should become null you could simply use a property setter
of the form {...set {b = value == "" ? null : value;}}. Almost an inverse
coalesce...

If this only applies during desrialization, well, for binary serialization
you could hook some combination of [OnDeserializing], [OnDeserialized] and
IDeserializationCallback... but xml is trickier... you could possibly
implement IXmlSerializable, but this isn't trivial.

Marc
Nov 2 '06 #3
Hi Roman Wagner/ Marc Gravell,
Many thanks for your replies.

I should not have written "missing". Actually, It's an empty
element.

As you said, i can use setter method to control the value. However,
i've a problem in that.

If the element is missing, then XmlSerializer tries to set the
default values (0 for int, false for bool) to the properties. Actually,
i should get "null" value if the element is passed as empty.

If i pass the empty element, the CLR throws exception in case if the
elment corresponds to types like int or bool.

More over i wanted to have null values for all the elements which
are sent as empty elements. The class can have any type of properties
like int, bool or another type of class. Since i wanted to have null
for all the properties which are sent as empty elements, i used
nullable types for primitive types like int? (for int).

The problem happens when the XmlSerializer tries to create the
object. Since the empty element is not the correct value for int? type,
it throws error even before coming to the setter method only.

Marc, by saying i need to implement IXmlSerializable, do you mean i
mean i need to implement the interface for all the entities(classes) i
need to crate from XML? It would not be ideal as i've to create many
classes from XML.

Thanks,
Kumar
Marc Gravell wrote:
Actually the XmlSerializer assigns "" (empty string) for a string
if the corresponding element is missing in the XML.

"Missing" is very different to "empty"; your B is empty, not missing.

Anyway, no: it doesn't; first it initialises the class using the field
initialisers and the default ctor. Then it applies all the *found* items,
else applies the [DefaultValue] (if one) to any that were omitted. If it
isn't in the xml it isn't set, so it would remain null. I guess your *real*
class is initialising it to "", or the data is in the xml.

If you really want to turn an *included* (blank) <B></Bto a null, then:

If *all* "" values should become null you could simply use a property setter
of the form {...set {b = value == "" ? null : value;}}. Almost an inverse
coalesce...

If this only applies during desrialization, well, for binary serialization
you could hook some combination of [OnDeserializing], [OnDeserialized] and
IDeserializationCallback... but xml is trickier... you could possibly
implement IXmlSerializable, but this isn't trivial.

Marc
Nov 3 '06 #4
Well, at the end of the day what you are describing is not the standard xml
serialization in the XmlSerializer sense. So to compensate, I see various
routes:
1: write your own serializer (hard work)
2: forget serializers and just do manual xml parsing yourself (also work)
3: have your objects implement IXmlSeriazable (hard work lots of times)
4: run the transmitted xml through e.g. xslt to convert between the form
that XmlSerializer likes and the form that you like... not sure how this
would compensate for missing xml fields that you need to generate an xsi:nul
entry for...
5: press to change the xml format? (not always achievable)

....

unfortunately, XmlSerializer is not as free-form as binary serialization,
which allows a few more tricks more easily (such as the before/after
"events" (attributed methods).

Marc
Nov 3 '06 #5
And an afterthought...

in most common usage, <element></elementwould be read "element is defined
as having a blank (i.e. empty string) value", which is what XmlSerializer is
doing. The omission of an element commonly means "leave it alone" / "default
value", with nullable types being handled a bit more subtly...

Just an observation...

Marc
Nov 3 '06 #6
Hi Marc,
The reason for this kind of requirement is that the same XML is used
for both insert and update actions. During the update I may get only
the updated elements. More over if the element is set to null, i'll get
an empty element. I need this empty element to distinguish from the
other non updated elements.

Many thanks for all your replies.

Regards,
Kumar
Marc Gravell wrote:
And an afterthought...

in most common usage, <element></elementwould be read "element is defined
as having a blank (i.e. empty string) value", which is what XmlSerializer is
doing. The omission of an element commonly means "leave it alone" / "default
value", with nullable types being handled a bit more subtly...

Just an observation...

Marc
Nov 6 '06 #7
Then presumably you are either doing the "WriteXml" step yourself
already, or consuming an existing feed that you aren't editing. In this
scenario, I might start looking at a simple, re-usable custom xml
parser using the component model... something as simple as:

* read (object) xml element
* identify object name [some custom mapping]
* read (property) xml element
* identify property name
* obtain object project via reflection / component-model
* set value
* loop property
* loop object

This would give you full control to interpret blank / missing as
whatever you want, yet without requiring custom code at an
object-by-object basis. Fundamentally this is very similar to the
approach taken by XmlSerializer. The other advantage is that it allows
you to decide very early on whether you are constructing a new object,
or applying the xml [effectively a diffgram] to an existing object;
XmlSerializer can only create.

On a purist note, I also like to distinguish between the empty string
and a null, but if this treatment works for your purposes...

Marc

Nov 6 '06 #8

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

Similar topics

4
by: Tom Esker | last post by:
I've got Javascript in a form that adds up all of the numbers in a column of form fields and displays a total. It works great if every field has an initial value of 0, but if any of them are null,...
3
by: Lynn | last post by:
Hi all, I am having problem when did the validation of XML document with Schema. my schema is like the following: <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="schema.xsd"...
3
by: Robb Gilmore | last post by:
Hello, We have a C#.NET app which is calling a Java webservice. We use the wsdl file exportted from the java webservice to create our web-reference in Visual Studio. We are able to create the...
0
by: Dana | last post by:
I am using the XMLTextWriter to build an XML string and pass it to the XMLDocument. When I get the data from SQL Server, some of the values passed to the XML are NULL in the database. When I try...
0
by: Benny Raymond | last post by:
reply to: benny@pocketrocks.com if possible: I'm trying to set up a hierarchy system in this database where each row can be related to a previous row. The problem is that when I go to...
4
by: Reuven Nisser | last post by:
Hi All, How to define an XML element with no value and no attribute? <X> <Y/> </X> And Y has no value? I've done it with:
4
by: keithb | last post by:
What is the correct syntax to detect whether a DataTable Row.ItemArray element is a null value? using: if (row.ItemArray == null ) does not seem to work. Thanks,
4
by: Eric Layman | last post by:
Hi everyone, Im puzzled by a NULL behaviour in SQL 2000 server. There is a column in the table that does not allow NULL. During data mining, the staff noted that, for that particular column,...
2
by: qwedster | last post by:
Folk! How to programattically check if null value exists in database table (using stored procedure)? I know it's possble in the Query Analyzer (see last SQL query batch statements)? But how...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.