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

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.ValueSpecified = 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 7845
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:=True in the XmlElementAttribute, you
will get <Age xsi:nil="true" />, which is not quite the same thing.
-Dino


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

using System.IO;
using System.Xml.Serialization;
// This is the default class generated from xsd.exe
[System.Xml.Serialization.XmlRootAttribute(Namespac e="", IsNullable=false)]
public class Person {

[System.Xml.Serialization.XmlElementAttribute(Form= System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string Name;

[System.Xml.Serialization.XmlElementAttribute(Form= System.Xml.Schema.XmlSchemaForm.Unqualified)]
public System.Single Age;

[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool AgeSpecified;
}


namespace Ionic {

public class XmlTextWriterFormattedNoDeclaration :
System.Xml.XmlTextWriter {
public XmlTextWriterFormattedNoDeclaration (System.IO.TextWriter w) :
base(w) { Formatting= System.Xml.Formatting.Indented;}
public override void WriteStartDocument () { }
}
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====================== ======================\nOriginal
XML:\n"+ OriginalXml);

XmlSerializer s1 = new XmlSerializer(typeof(Person));
Person p= null;
using (System.IO.StringReader sr= new
System.IO.StringReader(OriginalXml)) {
p = (Person) s1.Deserialize(sr);
}

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

// use a custom TextWriter to suppress the XML declaration

System.Console.WriteLine("\n====================== ======================\nOriginal
values:");
s1.Serialize(new
XmlTextWriterFormattedNoDeclaration(System.Console .Out), p, ns);
System.Console.WriteLine("\n");

System.Console.WriteLine("\n====================== ======================\nChanging
the name does not change the age:");
p.Name= "Bob";
s1.Serialize(new
XmlTextWriterFormattedNoDeclaration(System.Console .Out), p, ns);
System.Console.WriteLine("\n");
System.Console.WriteLine("\n====================== ======================\nUn-specifying
the Age results in this:");
p.AgeSpecified= false;
s1.Serialize(new
XmlTextWriterFormattedNoDeclaration(System.Console .Out), p, ns);
System.Console.WriteLine("\n");
string OriginalXml2=
"<Person>\n" +
" <Name>Shirley</Name>\n" +
" <Age />\n" +
"</Person>\n" +
"";
System.Console.WriteLine("\n====================== ======================\nCase
2: Original XML:\n"+ OriginalXml2);
p=null;
try {
System.Console.WriteLine("\n(De-serializing from this will
fail...)\n");
using (System.IO.StringReader sr= new
System.IO.StringReader(OriginalXml2)) {
p = (Person) s1.Deserialize(sr);
}
}
catch (System.InvalidOperationException ex1) {
System.Console.WriteLine("As Expected, an Exception was generated:
" + ex1);

}

if (p!= null) {
System.Console.WriteLine("\n====================== ======================\nOriginal
values:");
s1.Serialize(new
XmlTextWriterFormattedNoDeclaration(System.Console .Out), p, ns);
System.Console.WriteLine("\n");
}

p= new Person();
p.Name= "Henry";
System.Console.WriteLine("\n====================== ======================\nNew
Instance, setting only Name:");
s1.Serialize(new
XmlTextWriterFormattedNoDeclaration(System.Console .Out), p, ns);
System.Console.WriteLine("\n");

p.Age= 66;
System.Console.WriteLine("\n====================== ======================\nalso
setting Ageon that instance:");
s1.Serialize(new
XmlTextWriterFormattedNoDeclaration(System.Console .Out), p, ns);
System.Console.WriteLine("\n");

p.AgeSpecified= true;
System.Console.WriteLine("\n====================== ======================\nand
now setting AgeSpecified:");
s1.Serialize(new
XmlTextWriterFormattedNoDeclaration(System.Console .Out), p, ns);
System.Console.WriteLine("\n");

}
catch (System.Exception e1) {
System.Console.WriteLine("Exception!\n" + e1);
}
}
}
}

----- End Code -----
"Kenny Mullican" <no***********@nowayemonarch.net> wrote in message
news:%2******************@TK2MSFTNGP11.phx.gbl...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.ValueSpecified = 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
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...
0
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...
5
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...
0
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...
7
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...
3
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...
2
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...
5
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...
5
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
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
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...
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
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.