473,761 Members | 1,764 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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>s ome 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 34871
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.Str ingBuilder sb = new System.Text.Str ingBuilder();
System.Xml.Seri alization.XmlSe rializer ser = new
System.Xml.Seri alization.XmlSe rializer(typeof (DemoClass));

Console.WriteLi ne("Not null");
DemoClass demo = new DemoClass();
demo.B = "Not Null";
ser.Serialize(n ew System.IO.Strin gWriter(sb), demo);
Console.WriteLi ne(sb.ToString( ));
demo = ser.Deserialize (new System.IO.Strin gReader(sb.ToSt ring()))
as DemoClass;
Console.WriteLi ne(demo.ToStrin g());
Console.WriteLi ne();

Console.WriteLi ne("Null");
sb = new System.Text.Str ingBuilder();
demo = new DemoClass();
ser.Serialize(n ew System.IO.Strin gWriter(sb), demo);
Console.WriteLi ne(sb.ToString( ));
demo = ser.Deserialize (new System.IO.Strin gReader(sb.ToSt ring()))
as DemoClass;
Console.WriteLi ne(demo.ToStrin g());

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.New Line + "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
IDeserializatio nCallback... but xml is trickier... you could possibly
implement IXmlSerializabl e, 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 IXmlSerializabl e, do you mean i
mean i need to implement the interface for all the entities(classe s) 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
IDeserializatio nCallback... but xml is trickier... you could possibly
implement IXmlSerializabl e, 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
11789
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, "NaN" displays as the total. I tried to add a test for a null value with the intent to skip adding that field to the accumulator for one iteration of the "for" loop, but it doesn't work. Can anyone tell me what I'm doing wrong? Below is the...
3
13536
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" xmlns:msprop="urn:schemas-microsoft-com:xml-msprop" elementFormDefault="qualified" targetNamespace="schema.xsd"> <xsd:element name="bookstore" type="bookstoreType" /> <xsd:complexType name="bookstoreType"> <xsd:sequence maxOccurs="unbounded">...
3
7091
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 parameter classes and call the webservice just fine. Our problem is, within our .Net app, we have some value objects ( like floats, for instance ) which are meant to be null. Since there is no null float, we use float.minvalue to indicate a...
0
2269
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 and run an update to database using the same XML string, (using SQL parameters to pass the selectsinglenode), the XML always shows the NULL values as an empty string "". This is then updating the database with an empty value rather than keeping...
0
1711
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 addTreeRow, it doesn't allow me to use Convert.DBNull for the childof column, even though I have nilable set to true. (All parent nodes have to be set to null, since they are not the child of any other row... especially the very first row, which will have...
4
2360
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
4239
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
2135
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, there are a few records that are empty. I do not specifically know whether they are "alt + 0160" character.
2
14659
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 can I pass null value as parameter to the database stored procedure programattically using C#? Although I can check for empty column (the following code passes string.Empty as parameter but how to pass null value?), I cannot check for null value...
0
9554
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9377
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10136
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9989
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9925
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9811
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7358
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5266
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3913
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.