473,800 Members | 2,388 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to: Omit Deafulted Elements from XML When Serializing

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

Public Property Name() As String
Get
Return m_Name
End Get
Set(ByVal Value As String)
m_Name = Value
End Set
End Property

Public Property Active() As Boolean
Get
Return m_Active
End Get
Set(ByVal Value As Boolean)
m_Active = Value
End Set
End Property

Public Property Address() As String
Get
Return m_Address
End Get
Set(ByVal Value As String)
m_Address = Value
End Set
End Property

End Class

If Name is "George" when I serialize the object then I don't want this
element to be included in the output. Similarly, if Active is "False" when
the object is serialized, then I don't want that element included in the
output either. Anything different, and they should be included.

Is there a way to do this, perhaps by tagging the property/element in some
way? I am using VS2003.

TIA

Charles
Jan 28 '06 #1
3 2349
(Apologies for any bad VB in advance - I'm a C# person)
For each field add a corresponding Boolean field & property suffixed with
Specified (and the property has attribute XmlIgnore), such as:

Public Class Test

Private m_Name As String = "George"
Private m_NameSpecified As Boolean = False

Public Property Name() As String
Get
Return m_Name
End Get
Set(ByVal Value As String)
m_Name = Value
m_NameSpecified = True
End Set
End Property

<XmlIgnore()>
Public Property NameSpecified() As Boolean
Get
Return m_NameSpecified
End Get
Set(ByVal Value As Boolean)
m_NameSpecified = Value
End Set
End Property

The framework on serializing each field looks for a field of type Boolean
with the field name suffixed with "Specified" . If this field exists and has
value False, the field will not be serialized.

Note that in the original field's Set accessor I set the XXXSpecified field
to True. This means that if I ever set the property then it will get
serialized; if I don't set it, it won't. If you specifically want it so that
if it's not "George" it will be serialized then that is easy enough for you
to change appropriately.

"Charles Law" <bl***@nowhere. com> wrote in message
news:%2******** ********@tk2msf tngp13.phx.gbl. ..
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

Public Property Name() As String
Get
Return m_Name
End Get
Set(ByVal Value As String)
m_Name = Value
End Set
End Property

Public Property Active() As Boolean
Get
Return m_Active
End Get
Set(ByVal Value As Boolean)
m_Active = Value
End Set
End Property

Public Property Address() As String
Get
Return m_Address
End Get
Set(ByVal Value As String)
m_Address = Value
End Set
End Property

End Class

If Name is "George" when I serialize the object then I don't want this
element to be included in the output. Similarly, if Active is "False" when
the object is serialized, then I don't want that element included in the
output either. Anything different, and they should be included.

Is there a way to do this, perhaps by tagging the property/element in some
way? I am using VS2003.

TIA

Charles

Jan 30 '06 #2
Hi Clive

That does exactly what I want. Thanks.

I have never seen this documented, can you point me to an MSDN description
of this feature?

Whilst looking myself, I came across another way that seems to work:

<ComponentModel .DefaultValue(" George")> _
Public Property Name() As String
Get
Return m_Name
End Get
Set(ByVal Value As String)
m_Name = Value
End Set
End Property

Name now does not get serialized when it returns "George". Also,
XmlAttributes.X mlDefaultValue can be used to do the same thing at runtime.
The only concern with this is that MSDN article KB325691 highlights that
Microsoft intend to change this behaviour in the next major version release
of the .NET framework. I haven't checked, but I wonder if this technique no
longer works in .NET 2.0.

Anyway, many thanks again.

Charles
"Clive Dixon" <cl************ *******@digita. noluncheonmeat. com> wrote in
message news:ei******** ******@TK2MSFTN GP12.phx.gbl...
(Apologies for any bad VB in advance - I'm a C# person)
For each field add a corresponding Boolean field & property suffixed with
Specified (and the property has attribute XmlIgnore), such as:

Public Class Test

Private m_Name As String = "George"
Private m_NameSpecified As Boolean = False

Public Property Name() As String
Get
Return m_Name
End Get
Set(ByVal Value As String)
m_Name = Value
m_NameSpecified = True
End Set
End Property

<XmlIgnore()>
Public Property NameSpecified() As Boolean
Get
Return m_NameSpecified
End Get
Set(ByVal Value As Boolean)
m_NameSpecified = Value
End Set
End Property

The framework on serializing each field looks for a field of type Boolean
with the field name suffixed with "Specified" . If this field exists and
has value False, the field will not be serialized.

Note that in the original field's Set accessor I set the XXXSpecified
field to True. This means that if I ever set the property then it will get
serialized; if I don't set it, it won't. If you specifically want it so
that if it's not "George" it will be serialized then that is easy enough
for you to change appropriately.

"Charles Law" <bl***@nowhere. com> wrote in message
news:%2******** ********@tk2msf tngp13.phx.gbl. ..
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

Public Property Name() As String
Get
Return m_Name
End Get
Set(ByVal Value As String)
m_Name = Value
End Set
End Property

Public Property Active() As Boolean
Get
Return m_Active
End Get
Set(ByVal Value As Boolean)
m_Active = Value
End Set
End Property

Public Property Address() As String
Get
Return m_Address
End Get
Set(ByVal Value As String)
m_Address = Value
End Set
End Property

End Class

If Name is "George" when I serialize the object then I don't want this
element to be included in the output. Similarly, if Active is "False"
when the object is serialized, then I don't want that element included in
the output either. Anything different, and they should be included.

Is there a way to do this, perhaps by tagging the property/element in
some way? I am using VS2003.

TIA

Charles


Jan 30 '06 #3
Charles,

I had quite forgotten about the other methods you discovered - have no idea
whether they still function in the same way in 2.0. The
'propertyNameSp ecified' method seems much more flexible though.

If you look in the VS2003 help for XmlSerializer class ('about XMLSerializer
class'), about half way down the page is the following (I suspect the MSDN
documentation for this will be identical):

Another option is to use a special pattern to create a Boolean field
recognized by the XmlSerializer, and to apply the XmlIgnoreAttrib ute to the
field. The pattern is created in the form of propertyNameSpe cified. For
example, if there is a field named "MyFirstNam e" you would also create a
field named "MyFirstNameSpe cified" that instructs the XmlSerializer whether
or not to generate the XML element named "MyFirstNam e". This is shown in the
following C# and Visual Basic example.
' Visual Basic
Public Class OptionalOrder
' This field's value shouldn't be serialized
' if it is uninitialized.
Public FirstOrder As String
' Use the XmlIgnoreAttrib ute to ignore the
' special field named "FirstOrderSpec ified".
<System.Xml.Ser ialization.XmlI gnoreAttribute> _
Public FirstOrderSpeci fied As Boolean
End Class

"Charles Law" <bl***@nowhere. com> wrote in message
news:OT******** *****@TK2MSFTNG P11.phx.gbl...
Hi Clive

That does exactly what I want. Thanks.

I have never seen this documented, can you point me to an MSDN description
of this feature?

Whilst looking myself, I came across another way that seems to work:
<ComponentModel .DefaultValue(" George")> _
Public Property Name() As String
Get
Return m_Name
End Get
Set(ByVal Value As String)
m_Name = Value
End Set
End Property

Name now does not get serialized when it returns "George". Also,
XmlAttributes.X mlDefaultValue can be used to do the same thing at runtime.
The only concern with this is that MSDN article KB325691 highlights that
Microsoft intend to change this behaviour in the next major version
release of the .NET framework. I haven't checked, but I wonder if this
technique no longer works in .NET 2.0.

Anyway, many thanks again.

Charles

Jan 30 '06 #4

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

Similar topics

1
1347
by: Jonas Hei | last post by:
Can someone please clarify the in which XML standard (and various parsers) handle sequence of elements in XML? 1. Are the following two documents same (syntactically and sematically)? a. <Data> <InitialQualifier>xyz</InitialQualifier> <Value>678</Value> <Value>524</Value> </Data>
7
4358
by: grwalker | last post by:
I have some classes that have the <Serializable()> attribute applied, which of course by default serializes the class properties as elements. What I would like to do is to be able to override this behavior at runtime to serialize the properties as attributes. I have been exploring the XMLAttributesOverrides classes and examples which claims: "you can create one set of serializable classes, but serialize the objects in multiple ways....
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
7
2828
by: fjlaga | last post by:
I have written an Office Add-in for Excel using VB.NET and the .NET 1.1 Framework (I have Visual Studio 2003 .NET ). All works great. I want to add a User Settings/Prefereneces dialog and allow the user to specify some settings and I need to persist these settings between runs. I made a serializable class which uses the BinaryFormatter to serialize/deserialize the setttings. Serialization works great. However, when I try to...
9
6485
by: Mark Olbert | last post by:
I'm trying to serialize (using XmlSerializer.Serialize) a class that I generated from an XSD schema using XSD.EXE /c. The problem I'm running into is that the root element needs to be unqualified, and the default namespace needs to be included on it as an attribute. The schema I'm using is this: <xs:schema xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:html="http://www.w3.org/TR/REC-html40"...
2
2892
by: =?Utf-8?B?UmF5IE1pdGNoZWxs?= | last post by:
Hi, I know this will sound like a lot of hand waving, and I'll be glad to supply some sample code if necessary, but I thought something obvious might jump out at someone without doing so. Anyway, I have a structure that has several members including an array of strings. I assign the elements of the string array from the .Text property of several TextBoxes. I then serialize the structure and write it to a file. However, when I...
12
4925
by: Cagdas Ozgenc | last post by:
Greetings, When directly serializing C++ structures to a file with the standard library functions giving the address of the data and length of structure using the sizeof operator, do I risk portability because of different compilers packing structures into different sizes or components of this structure to different address boundaries (for example placing in multiples of 4 on a 32bit system)? Once the file is serialized, does the same...
8
1697
by: swsdam | last post by:
Thank you for even reading this... I have an xml doc that feeds into html. I am being passed the xml via asp.net. I have used xsl to create an html. Now I'm being asked to let the user omit which elements get copied to new xml (via another xsl?). I would like to present the xml elements to my user and let them select which elements to copy onto another xml doc by clicking a checkbox. Is this possible and how? So far I am thiking maybe I...
0
1248
by: dph5010 | last post by:
I'm trying to make an object that will reflect the response from isbndb.com's API so I can serialize the results into my code. Right now I have code that works, however, the structure isn't quite the same as what isbndb.com uses. My problem, is serializing the array of BookData objects and putting attributes into the array wrapper tag <BookList>. Right now, I'm just using a custom object called BookList to add attributes to the element, but...
0
978
by: =?Utf-8?B?RGF2ZSBU?= | last post by:
From a web service I'm serializing out an object model. Is there a way to only include those elements of the object model which actually contain data?
0
9695
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
9555
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
10514
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...
1
10260
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
10042
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...
0
9099
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...
1
7588
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
6826
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
3770
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.