473,287 Members | 1,643 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,287 software developers and data experts.

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.Collections;
using System.ComponentModel;
using System.IO;
using System.Xml.Serialization;

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

[DefaultValue("InitialValue")]
public string TheString = "InitialValue";

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

public SimpleClass()
{
}
}

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

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

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

SimpleCollection InstanceToSerialize = new SimpleCollection();
InstanceToSerialize.Add(new SimpleClass(true, "I am true"));
InstanceToSerialize.Add(new SimpleClass(false, "I am false"));
InstanceToSerialize.Add(new SimpleClass(true, "true #2"));
InstanceToSerialize.Add(new SimpleClass(false, "false #2"));

// Serialize with the pre configured default values.
XmlSerializer Serializer = new
XmlSerializer(InstanceToSerialize.GetType());
StringWriter XMLStringWriter = new StringWriter();
Serializer.Serialize(XMLStringWriter, InstanceToSerialize);
Console.WriteLine("\nWITHOUT Overrides: \n" +
XMLStringWriter.ToString());

// Attempt to serialize as if there were no default values set.
XmlAttributeOverrides ExplicitOverrides = new
XmlAttributeOverrides();

// Setup the override default value for TheString.
XmlAttributes TheStringAttributes = new XmlAttributes();
TheStringAttributes.XmlDefaultValue = "SOME TEXT THE STRING WILLL
NEVER CONTAIN";
ExplicitOverrides.Add(typeof(SimpleClass), "TheString",
TheStringAttributes);

// Setup the override default value for TheBool.
XmlAttributes TheBoolAttributes = new XmlAttributes();
TheBoolAttributes.XmlDefaultValue = false; // Works, but
only for a single instance, fails for an array or collection.
// TheBoolAttributes.XmlDefaultValue = null; // Throws a
file not found exception
// TheBoolAttributes.XmlDefaultValue = new object(); // Throws an
InvalidOperationException: The default value type, System.Object, is
unsupported.
// TheBoolAttributes.XmlDefaultValue = ""; // Throws a
file not found exception
// TheBoolAttributes.XmlDefaultValue = 6; // Throws a
file not found exception
ExplicitOverrides.Add(typeof(SimpleClass), "TheBool",
TheBoolAttributes);

XmlSerializer SerializerOverrides = new
XmlSerializer(InstanceToSerialize.GetType(), ExplicitOverrides);
XMLStringWriter = new StringWriter();
SerializerOverrides.Serialize(XMLStringWriter,
InstanceToSerialize);
Console.WriteLine("\nWITH Overrides: \n" +
XMLStringWriter.ToString());
}
}
}

// Sample Output:
//WITHOUT Overrides:
//<?xml version="1.0" encoding="utf-16"?>
//<ArrayOfSimpleClass 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>false</TheBool>
//<TheString>I am false</TheString>
//</SimpleClass>
//<SimpleClass>
//<TheString>true #2</TheString>
//</SimpleClass>
//<SimpleClass>
//<TheBool>false</TheBool>
//<TheString>false #2</TheString>
//</SimpleClass>
//</ArrayOfSimpleClass>
//
//WITH Overrides:
//<?xml version="1.0" encoding="utf-16"?>
//<ArrayOfSimpleClass 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>true #2</TheString>
//</SimpleClass>
//<SimpleClass>
//<TheString>false #2</TheString>
//</SimpleClass>
//</ArrayOfSimpleClass>
Nov 11 '05 #1
0 3937

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

Similar topics

14
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...
0
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...
0
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
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...
5
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
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...
2
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...
0
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...
4
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...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...

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.