473,581 Members | 2,338 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Override DefaultValue during XML Serialization

// Is there any way to override the XML Serialization of the following
SimpleClass
// to turn off the DefaultValue of a boolean? Sure, I can override
the DefaultValue from
// true to false, but that is not what I want/need. I really need to
just override the fact
// that the developer ever supplied a DefaultValue. Setting an
override DefaultValue of null
// or "new object()" errors. Any help would be appreciated.

using System;
using System.Collecti ons;
using System.Componen tModel;
using System.IO;
using System.Xml.Seri alization;

namespace XMLStub
{
/// <summary>A simple class to be XML Serialized.</summary>
public class SimpleClass
{
[DefaultValue(tr ue)]
public bool TheBool = true;

[DefaultValue("I nitialValue")]
public string TheString = "InitialVal ue";

public SimpleClass(boo l NewBool, string NewString)
{
TheBool = NewBool;
TheString = NewString;
}

public SimpleClass()
{
}
}

/// <summary>A simple class that holds a collection of
SimpleClass.</summary>
public class SimpleCollectio n : CollectionBase
{
public SimpleClass this[int Index]
{
get { return((SimpleC lass)List[Index]); }
}

public void Add(SimpleClass NewSimpleClass)
{
List.Add(NewSim pleClass);
}
}

class gMain
{
[STAThread]
static void Main(string[] args)
{
//SimpleClass InstanceToSeria lize = new SimpleClass();

SimpleCollectio n InstanceToSeria lize = new SimpleCollectio n();
InstanceToSeria lize.Add(new SimpleClass(tru e, "I am true"));
InstanceToSeria lize.Add(new SimpleClass(fal se, "I am false"));
InstanceToSeria lize.Add(new SimpleClass(tru e, "true #2"));
InstanceToSeria lize.Add(new SimpleClass(fal se, "false #2"));

// Serialize with the pre configured default values.
XmlSerializer Serializer = new
XmlSerializer(I nstanceToSerial ize.GetType());
StringWriter XMLStringWriter = new StringWriter();
Serializer.Seri alize(XMLString Writer, InstanceToSeria lize);
Console.WriteLi ne("\nWITHOUT Overrides: \n" +
XMLStringWriter .ToString());

// Attempt to serialize as if there were no default values set.
XmlAttributeOve rrides ExplicitOverrid es = new
XmlAttributeOve rrides();

// Setup the override default value for TheString.
XmlAttributes TheStringAttrib utes = new XmlAttributes() ;
TheStringAttrib utes.XmlDefault Value = "SOME TEXT THE STRING WILLL
NEVER CONTAIN";
ExplicitOverrid es.Add(typeof(S impleClass), "TheString" ,
TheStringAttrib utes);

// Setup the override default value for TheBool.
XmlAttributes TheBoolAttribut es = new XmlAttributes() ;
TheBoolAttribut es.XmlDefaultVa lue = false; // Works, but
only for a single instance, fails for an array or collection.
// TheBoolAttribut es.XmlDefaultVa lue = null; // Throws a
file not found exception
// TheBoolAttribut es.XmlDefaultVa lue = new object(); // Throws an
InvalidOperatio nException: The default value type, System.Object, is
unsupported.
// TheBoolAttribut es.XmlDefaultVa lue = ""; // Throws a
file not found exception
// TheBoolAttribut es.XmlDefaultVa lue = 6; // Throws a
file not found exception
ExplicitOverrid es.Add(typeof(S impleClass), "TheBool",
TheBoolAttribut es);

XmlSerializer SerializerOverr ides = new
XmlSerializer(I nstanceToSerial ize.GetType(), ExplicitOverrid es);
XMLStringWriter = new StringWriter();
SerializerOverr ides.Serialize( XMLStringWriter ,
InstanceToSeria lize);
Console.WriteLi ne("\nWITH Overrides: \n" +
XMLStringWriter .ToString());
}
}
}

// Sample Output:
//WITHOUT Overrides:
//<?xml version="1.0" encoding="utf-16"?>
//<ArrayOfSimpleC lass xmlns:xsd="http ://www.w3.org/2001/XMLSchema"
xmlns:xsi="http ://www.w3.org/2001/XMLSchema-instance">
//<SimpleClass>
//<TheString>I am true</TheString>
//</SimpleClass>
//<SimpleClass>
//<TheBool>fals e</TheBool>
//<TheString>I am false</TheString>
//</SimpleClass>
//<SimpleClass>
//<TheString>tr ue #2</TheString>
//</SimpleClass>
//<SimpleClass>
//<TheBool>fals e</TheBool>
//<TheString>fals e #2</TheString>
//</SimpleClass>
//</ArrayOfSimpleCl ass>
//
//WITH Overrides:
//<?xml version="1.0" encoding="utf-16"?>
//<ArrayOfSimpleC lass xmlns:xsd="http ://www.w3.org/2001/XMLSchema"
xmlns:xsi="http ://www.w3.org/2001/XMLSchema-instance">
//<SimpleClass>
//<TheBool>true </TheBool>
//<TheString>I am true</TheString>
//</SimpleClass>
//<SimpleClass>
//<TheString>I am false</TheString>
//</SimpleClass>
//<SimpleClass>
//<TheBool>true </TheBool>
//<TheString>tr ue #2</TheString>
//</SimpleClass>
//<SimpleClass>
//<TheString>fals e #2</TheString>
//</SimpleClass>
//</ArrayOfSimpleCl ass>
Nov 11 '05 #1
0 3981

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

Similar topics

14
1890
by: Maurice Mertens | last post by:
Hi, I have an Access database in which I defined default values for certain columns. On my windows forms I've got controls bound to the dataset, The problem is that when I add a new row to the dataset my controls don't have the defaultvalue entered in the database. Is it possible to retrieve the defaultvalue for the column from the...
0
2748
by: | last post by:
The code is below.. I want to be able to override two classes to the same element name... I've commented out the code which I cant get to work... the base of the code is an extention of one of the .Net examples... using System.Xml; using System.Xml.Serialization; using System.Collections; using System.IO;
0
4313
by: Mike | last post by:
), "new MenuItem")] public MenuItem MenuItems = new MenuItem; I am trying to get rid of all the <MenuItem /> tags when serializing Thanks...
11
6609
by: Rangi Keen | last post by:
I am instantiating an XmlSerializer using the XmlSerializer(Type) constructor. This works most of the time, but sometimes I get a timeout during the process. I'm using the same type in all cases and it has happened on multiple computers ranging from 500 MHz to 2.6 GHz. Does anyone know why the csc.exe process would time out in this case? It...
5
1432
by: schneider | last post by:
Hello, Have an issue with a property using the DefaultValue(True) attribute. Imports System.ComponentModel Public Class Class1 Private m_testValue As Boolean
0
948
by: Carlo, MCP | last post by:
Good morning, sorry for the lenght of the code, but it's six months that I've this problem. The following code is an extreme simplification of the original code, that is much more complex. The problem, however, occours in the following code at all. It's easy copy the following code for reproducing the problem. This is a class that simply...
2
2464
by: Angelos Karantzalis | last post by:
Hi y'all, we're using a bunch of classes in a project, that we wanted to convert to-from xml easily. So, we defined XmlAttribute annotations for our class members and all worked fine. The Xml stream came from an external source with a custom xml schema, so we had no alternative. However, along the way we came to the point that we must...
0
1958
by: Chris McDonough | last post by:
ElementTree's XML serialization routine implied by tree._write(file, node, encoding, namespaces looks like this (elided): def _write(self, file, node, encoding, namespaces): # write XML to file tag = node.tag if tag is Comment: file.write("<!-- %s -->" % _escape_cdata(node.text, encoding)) elif tag is ProcessingInstruction:...
4
5344
by: SteveT | last post by:
I have a boolean property that I want to serialize to disk using XmlSerializer. I noticed that if the property includes the attribute "DefaultValue(true)" or "DefaultValue(false)" that the property will not serialilze to an XML file. If the attribute is removed the serialization occurs just fine. Is there a way around this bug? This...
0
7862
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...
0
8144
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. ...
0
8301
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...
1
7894
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...
0
8169
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...
0
3820
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2300
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
1
1400
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1132
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...

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.