473,948 Members | 12,236 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How do you prevent null elements from being serialized?

I am using complex types in order to support serialization/deserialization
of floating point numbers, since floating points can't be null.
I've seen how to suppress attributes that are "not specified", such as
having a float member called Value, and a bool member called ValueSpecified.
This instructs the XML Serializer to omit that attribute altogether if it
wasn't "Specified" . But how can I tell it to omit the XML element
altogether?
Here's the problem:
I deserialize an object that looks like this:
<person>

<name>Joe</name>

<age>37</age>

</person>

When deserialized, I get an object of type person, with a field age of type
floatType which has Value = 37 and ValueSpecified = false.
If I change name to "Bob" (p.name = "Bob"), and then immediately serialize
that object to XML, I get:
<person>

<name>Bob</name>

<age />

</person>

This indicates that age should now be null (if I pass this off to a SOAP
server for instance), or if that value is not allowed to be nulled, then I
get a SOAP exception.
If I explicitly set p.age.ValueSpec ified = true or set p.age.Value = 36
(which implicitly sets ValueSpecified to true)
Then I get the expected
<person>

<name>Bob</name>

<age>36</age>

</person>

What I would like to see happen is if ValueSpecified is false, then just
leave that element off altogether. Is there a way to do this?
Thanks for your help

Kenny
Nov 12 '05 #1
1 7880
Kenny, you don't show your code, but something fishy is going on.

1. De-serializing from

<person>
<name>Joe</name>
<age>37</age>
</person>

....I get name=Joe, Age=37 and AgeSpecified = true (not false as you report).

Also, changing the Name from Joe to Bob should not affect Age or
AgeSpecified, as you report. Also, changing Age does not directly affect
AgeSpecified. These things are true, unless you have put some non-default
handling in the property getter/setter.

What I would like to see happen is if ValueSpecified is false, then just
leave that element off altogether. Is there a way to do this?
This is the default behavior?, so I don't understand why you are asking
this. The code enclosed below demonstrates this, and some other interesting
things in XML serialization.

In fact you have to do something special in order to get an empty element
(eg "<Age />") to appear in an XML stream output from the .NET XML
Serializer. If you use isnullable:=Tru e in the XmlElementAttri bute, you
will get <Age xsi:nil="true" />, which is not quite the same thing.
-Dino


----- Begin Code -----
// XmlIgnoreTest.c s
//
// Exercises some of the XmlIgnore stuff
//
// compile with:
//
// (c) Ionic Shade
// Wed, 17 Nov 2004 10:02
//

using System.IO;
using System.Xml.Seri alization;
// This is the default class generated from xsd.exe
[System.Xml.Seri alization.XmlRo otAttribute(Nam espace="", IsNullable=fals e)]
public class Person {

[System.Xml.Seri alization.XmlEl ementAttribute( Form=System.Xml .Schema.XmlSche maForm.Unqualif ied)]
public string Name;

[System.Xml.Seri alization.XmlEl ementAttribute( Form=System.Xml .Schema.XmlSche maForm.Unqualif ied)]
public System.Single Age;

[System.Xml.Seri alization.XmlIg noreAttribute()]
public bool AgeSpecified;
}


namespace Ionic {

public class XmlTextWriterFo rmattedNoDeclar ation :
System.Xml.XmlT extWriter {
public XmlTextWriterFo rmattedNoDeclar ation (System.IO.Text Writer w) :
base(w) { Formatting= System.Xml.Form atting.Indented ;}
public override void WriteStartDocum ent () { }
}
public class TestDriver {

static void Main(string[] args) {

try {

string OriginalXml=
"<Person>\n " +
" <Name>Joe</Name>\n" +
" <Age>37</Age>\n" +
"</Person>\n" +
"";

System.Console. WriteLine("\n== =============== =============== ============\nO riginal
XML:\n"+ OriginalXml);

XmlSerializer s1 = new XmlSerializer(t ypeof(Person));
Person p= null;
using (System.IO.Stri ngReader sr= new
System.IO.Strin gReader(Origina lXml)) {
p = (Person) s1.Deserialize( sr);
}

// suppress default namespace entries in the root elt
XmlSerializerNa mespaces ns = new XmlSerializerNa mespaces();
ns.Add( "", "" );

// use a custom TextWriter to suppress the XML declaration

System.Console. WriteLine("\n== =============== =============== ============\nO riginal
values:");
s1.Serialize(ne w
XmlTextWriterFo rmattedNoDeclar ation(System.Co nsole.Out), p, ns);
System.Console. WriteLine("\n") ;

System.Console. WriteLine("\n== =============== =============== ============\nC hanging
the name does not change the age:");
p.Name= "Bob";
s1.Serialize(ne w
XmlTextWriterFo rmattedNoDeclar ation(System.Co nsole.Out), p, ns);
System.Console. WriteLine("\n") ;
System.Console. WriteLine("\n== =============== =============== ============\nU n-specifying
the Age results in this:");
p.AgeSpecified= false;
s1.Serialize(ne w
XmlTextWriterFo rmattedNoDeclar ation(System.Co nsole.Out), p, ns);
System.Console. WriteLine("\n") ;
string OriginalXml2=
"<Person>\n " +
" <Name>Shirley </Name>\n" +
" <Age />\n" +
"</Person>\n" +
"";
System.Console. WriteLine("\n== =============== =============== ============\nC ase
2: Original XML:\n"+ OriginalXml2);
p=null;
try {
System.Console. WriteLine("\n(D e-serializing from this will
fail...)\n");
using (System.IO.Stri ngReader sr= new
System.IO.Strin gReader(Origina lXml2)) {
p = (Person) s1.Deserialize( sr);
}
}
catch (System.Invalid OperationExcept ion ex1) {
System.Console. WriteLine("As Expected, an Exception was generated:
" + ex1);

}

if (p!= null) {
System.Console. WriteLine("\n== =============== =============== ============\nO riginal
values:");
s1.Serialize(ne w
XmlTextWriterFo rmattedNoDeclar ation(System.Co nsole.Out), p, ns);
System.Console. WriteLine("\n") ;
}

p= new Person();
p.Name= "Henry";
System.Console. WriteLine("\n== =============== =============== ============\nN ew
Instance, setting only Name:");
s1.Serialize(ne w
XmlTextWriterFo rmattedNoDeclar ation(System.Co nsole.Out), p, ns);
System.Console. WriteLine("\n") ;

p.Age= 66;
System.Console. WriteLine("\n== =============== =============== ============\na lso
setting Ageon that instance:");
s1.Serialize(ne w
XmlTextWriterFo rmattedNoDeclar ation(System.Co nsole.Out), p, ns);
System.Console. WriteLine("\n") ;

p.AgeSpecified= true;
System.Console. WriteLine("\n== =============== =============== ============\na nd
now setting AgeSpecified:") ;
s1.Serialize(ne w
XmlTextWriterFo rmattedNoDeclar ation(System.Co nsole.Out), p, ns);
System.Console. WriteLine("\n") ;

}
catch (System.Excepti on e1) {
System.Console. WriteLine("Exce ption!\n" + e1);
}
}
}
}

----- End Code -----
"Kenny Mullican" <no***********@ nowayemonarch.n et> wrote in message
news:%2******** **********@TK2M SFTNGP11.phx.gb l...I am using complex types in order to support serialization/deserialization
of floating point numbers, since floating points can't be null.
I've seen how to suppress attributes that are "not specified", such as
having a float member called Value, and a bool member called
ValueSpecified. This instructs the XML Serializer to omit that attribute
altogether if it wasn't "Specified" . But how can I tell it to omit the
XML element altogether?
Here's the problem:
I deserialize an object that looks like this:
<person>

<name>Joe</name>

<age>37</age>

</person>

When deserialized, I get an object of type person, with a field age of
type floatType which has Value = 37 and ValueSpecified = false.
If I change name to "Bob" (p.name = "Bob"), and then immediately serialize
that object to XML, I get:
<person>

<name>Bob</name>

<age />

</person>

This indicates that age should now be null (if I pass this off to a SOAP
server for instance), or if that value is not allowed to be nulled, then I
get a SOAP exception.
If I explicitly set p.age.ValueSpec ified = true or set p.age.Value = 36
(which implicitly sets ValueSpecified to true)
Then I get the expected
<person>

<name>Bob</name>

<age>36</age>

</person>

What I would like to see happen is if ValueSpecified is false, then just
leave that element off altogether. Is there a way to do this?
Thanks for your help

Kenny

Nov 12 '05 #2

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

Similar topics

6
7984
by: Squeamz | last post by:
Hello, Say I create a class ("Child") that inherits from another class ("Parent"). Parent's destructor is not virtual. Is there a way I can prevent Parent's destructor from being called when a Child object goes out of scope? Specifically, I am dealing with a C library that provides a function that must be called to "destruct" a particular struct (this struct is dynamically allocated by another provided function). To avoid memory
0
1408
by: Ryan Gilchrist | last post by:
Hi, There appears to be a difference in how null arrays and collections are deserialized using XmlSerializer. A null array is serialized into nothing, then deserialized back to null again (which one could argue is the correct behaviour), while a collection is serialized into nothing (like the array) but then deserialized into a collection instance with 0 elements. Obviously, you'd have trouble telling the difference between a null...
5
24769
by: David Sworder | last post by:
Hi, I've created a UserControl-derived class called MyUserControl that is able to persist and subsequently reload its state. It exposes two methods as follows: public void Serialize(Stream s); public void Deserialize(Stream s); Within the MyUserControl class, there is a field of type MyInnerClass
0
2008
by: Pierre | last post by:
Hi, I'm trying to select specific nodes from a XmlDocument filled with a serialized object and to insert these nodes into another XmlDocument. The object is well serialized (see below). From a normal XmlDoc to another I don't have any issue, the nodes are copied but then with this serialized object it doesn't seem to work. The C# code:
7
3680
by: Neal Andrews | last post by:
Hi All, Does anyone know how to stop Events from being serialized in a class that uses the <Serializable()> attribute? I have tried using the <NonSerialized()> attribute but for some bizarre reason, it is not allowed on events. I am using VS 2003, if that makes any difference. The only thing I can think of is to wrap all the events in a separate class and then not to mark the class as Serializable.
3
3346
by: Jim Hsu | last post by:
when I use the XmlWebSerivce to response the xmlelement to Web Service client. the ASP.net plumbing work ( the XmlSerializer in WebServices ) will serialize the XML if we can control the wrapper class , I can set the XmlSchemaForm.None or Qualified so that there will no be a 'xmlns=""' in the following namespace, but I don't know how to do that in WebService plumbing. this null namespace will makes my web service wrapper class complains....
2
331
by: Charles Law | last post by:
I have a complex object that I am serializing, and I would like to omit elements that have a default value. For example, if I have a class as follows Public Class Test Private m_Name As String = "George" Private m_Active As Boolean = False Private m_Address As String
5
3411
by: EqDev | last post by:
I have a class that is a control derived from UserControl. I want to use serialization and deserialization with this calss but I get an exception "Cannot serialize member System.ComponentModel.Component.Site of type System.ComponentModel.ISite because it is an interface.". I am not interested in serializing any member from the base class only the properties in the derived class. How can I prevent the entire base class from being...
5
4930
by: CindyRob | last post by:
Using .NET framework 1.1 SP1, .NET framework SDK 1.1 SP1, Visual Studio .NET 2003, hotfixes 892202 and 823639. I create a proxy class using wsdl.exe, and in the serialized XML request, I see that any elements that are nested elements in the schema (not global elements) have their namespaces set to the null namespace. I can see that the proxy classes have serialization attributes specifying these nested elements as unqualified: ///...
0
10167
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
11582
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
11181
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
11355
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
9898
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6120
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...
0
6340
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4543
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3547
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.