473,472 Members | 1,702 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

XmlSerializer

Hi,

I have created a class, named FormField , which basically contains two
fields, name and value. I have set the [XmlRoot(ElementName="field",
Namespace=null)] tag before the class and the field is set as an
XmlAttribute whil the name as XmlText.

In my main class, i have created an arraylist which contains a collection of
this class FormField. Basically its:

public void Add( string sName, string sValue )
{
FormField ff = new FormField( sName, sValue );
m_alFields.Add( ff );
}

The problem arise when i try to serialise this collection. For some reason,
none of the fields are present, only the root element is. The code i use is:

XmlSerializer serializer = new XmlSerializer(typeof(FormFieldCollection),
new System.Type[] { typeof( FormField ) } );
StringWriter writer = new StringWriter();
serializer.Serialize( writer, this);

[note: FormFieldCollection is the main class]

The result i get is:

<?xml version= "1.0" encoding= "utf-16"?>
<fieldsRoot xmlns:xsd= "http://www.w3.org/2001/XMLSchema" xmlns:xsi=
"http://www.w3.org/2001/XMLSchema-instance" />

Whilst the result i want is:

<?xml version= "1.0" encoding= "utf-16"?>
<fieldsRoot>
<field name = [name]>[value]</field>
</fieldsRoot>

Furthermore is there a way, to ommit the default namespaces?

Thanks in advance.
Nov 12 '05 #1
3 4477
> Whilst the result i want is:

<?xml version= "1.0" encoding= "utf-16"?>
<fieldsRoot>
<field name = [name]>[value]</field>
</fieldsRoot>

Loui, you don't show your code for the collection class; I suspect that is
the problem. Attached below is some code that does what you want.
Furthermore is there a way, to ommit the default namespaces?
Yes, the way to do this is explicitly specify a collection of namespaces to
include in the root element, and in that collection, add a blank namespace.
so,

XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add( "", "" );
XmlSerializer s1 = new XmlSerializer(typeof(FormFieldCollection));
FormFieldCollection fc= new FormFieldCollection();
// add elements here ....
s1.Serialize(System.Console.Out, fc, ns);

This only works if xsi and xsd are *not* used in your instance. If either
one is required, it will appear in the serialized stream.
-D

--
Dino Chiesa
Microsoft Developer Division
d i n o c h @ OmitThis . m i c r o s o f t . c o m

---- begin code ----
using System.IO;
using System.Xml.Serialization;

[XmlRoot(ElementName="field", Namespace=null)]
public class FormField {

public FormField() {}
public FormField(string Name, string Value) {
name= Name;
value= Value;
}
[XmlAttribute]
public string name;

[XmlText]
public string value;
}
// here is the collection class
// Note: cannot use attributes on a type derived from CollectionBase !
//
// [XmlRoot("fieldsRoot", Namespace="", IsNullable=false)]
// [XmlType("fieldsRoot", Namespace="")]
public class FormFieldCollection : System.Collections.CollectionBase {
public FormFieldCollection() {}

public int Add(FormField field)
{
return List.Add(field);
}

public FormField this[int index]
{
get { return(( FormField)List[index]); }
set { List[index] = value; }
}
}

namespace Ionic {

// useful for suppressing the XML Declaration line
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 {

FormFieldCollection fc= new FormFieldCollection();

XmlSerializer s1 = new XmlSerializer(typeof(FormFieldCollection));

// explicitly specify the namespace collection to suppress default
namespace entries in the root elt:
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add( "", "" );
fc.Add(new FormField("one", "Remember the human"));
fc.Add(new FormField("two", "Adhere to the same standards of
behavior online that you follow in real life"));
fc.Add(new FormField("three", "Know where you are in cyberspace"));

// use a custom TextWriter to suppress the XML declaration
System.Console.WriteLine("\n====================== ======================\nSerialized:");
s1.Serialize(new
XmlTextWriterFormattedNoDeclaration(System.Console .Out), fc, ns);
System.Console.WriteLine("\n");

// apply a root override (not possible in code attributes on a
CollectionBase)
System.Console.WriteLine("\n====================== ======================\nSerialized
using a root override:");
XmlRootAttribute xRoot1 = new XmlRootAttribute();
xRoot1.Namespace = ""; // "urn:www.example.org";
xRoot1.ElementName = "fieldsRoot";

XmlSerializer s2 = new XmlSerializer(typeof(FormFieldCollection),
xRoot1);

s2.Serialize(new
XmlTextWriterFormattedNoDeclaration(System.Console .Out), fc, ns);
System.Console.WriteLine("\n");

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

---- end code ----

"Loui Mercieca" <lo**@gfi.com> wrote in message
news:%2***************@TK2MSFTNGP14.phx.gbl... Hi,

I have created a class, named FormField , which basically contains two
fields, name and value. I have set the [XmlRoot(ElementName="field",
Namespace=null)] tag before the class and the field is set as an
XmlAttribute whil the name as XmlText.

In my main class, i have created an arraylist which contains a collection
of this class FormField. Basically its:

public void Add( string sName, string sValue )
{
FormField ff = new FormField( sName, sValue );
m_alFields.Add( ff );
}

The problem arise when i try to serialise this collection. For some
reason, none of the fields are present, only the root element is. The code
i use is:

XmlSerializer serializer = new XmlSerializer(typeof(FormFieldCollection),
new System.Type[] { typeof( FormField ) } );
StringWriter writer = new StringWriter();
serializer.Serialize( writer, this);

[note: FormFieldCollection is the main class]

The result i get is:

<?xml version= "1.0" encoding= "utf-16"?>
<fieldsRoot xmlns:xsd= "http://www.w3.org/2001/XMLSchema" xmlns:xsi=
"http://www.w3.org/2001/XMLSchema-instance" />

Whilst the result i want is:

<?xml version= "1.0" encoding= "utf-16"?>
<fieldsRoot>
<field name = [name]>[value]</field>
</fieldsRoot>

Furthermore is there a way, to ommit the default namespaces?

Thanks in advance.

Nov 12 '05 #2
Hi,

I did manage to do this by using the following code:

//Create a new empty name spave, used to ovveride the default
XmlSerializerNamespaces emptyNamespace = new XmlSerializerNamespaces();
emptyNamespace.Add("", "");

//Declare a new XmlSerializer instance, with the type of an array of
FormField, and the default attribute.
XmlSerializer serializer = new XmlSerializer(typeof(FormField[]));

//Declare a new StringWriter used as the place to store the serialized xml
StringWriter writer = new StringWriter();

//Serialize the array, using the empty namespace
serializer.Serialize( writer, this.Fields,emptyNamespace );

However now i face a new problem. Although i am declaring and
XmlRootAttribute i am still getting the class name as the the root. What am
i doing wrong?

The declaration is as follows
[XmlRootAttribute("field")]
public class FormField

The result i get is as follows
<fieldsRoot>
<FormField name = [name]>[value]</FormField>
</fieldsRoot>
"Dino Chiesa [Microsoft]" <di****@online.microsoft.com> wrote in message
news:eT**************@TK2MSFTNGP14.phx.gbl...
Whilst the result i want is:

<?xml version= "1.0" encoding= "utf-16"?>
<fieldsRoot>
<field name = [name]>[value]</field>
</fieldsRoot>


Loui, you don't show your code for the collection class; I suspect that is
the problem. Attached below is some code that does what you want.
Furthermore is there a way, to ommit the default namespaces?


Yes, the way to do this is explicitly specify a collection of namespaces
to include in the root element, and in that collection, add a blank
namespace.
so,

XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add( "", "" );
XmlSerializer s1 = new XmlSerializer(typeof(FormFieldCollection));
FormFieldCollection fc= new FormFieldCollection();
// add elements here ....
s1.Serialize(System.Console.Out, fc, ns);

This only works if xsi and xsd are *not* used in your instance. If
either one is required, it will appear in the serialized stream.
-D

--
Dino Chiesa
Microsoft Developer Division
d i n o c h @ OmitThis . m i c r o s o f t . c o m

---- begin code ----
using System.IO;
using System.Xml.Serialization;

[XmlRoot(ElementName="field", Namespace=null)]
public class FormField {

public FormField() {}
public FormField(string Name, string Value) {
name= Name;
value= Value;
}
[XmlAttribute]
public string name;

[XmlText]
public string value;
}
// here is the collection class
// Note: cannot use attributes on a type derived from CollectionBase !
//
// [XmlRoot("fieldsRoot", Namespace="", IsNullable=false)]
// [XmlType("fieldsRoot", Namespace="")]
public class FormFieldCollection : System.Collections.CollectionBase {
public FormFieldCollection() {}

public int Add(FormField field)
{
return List.Add(field);
}

public FormField this[int index]
{
get { return(( FormField)List[index]); }
set { List[index] = value; }
}
}

namespace Ionic {

// useful for suppressing the XML Declaration line
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 {

FormFieldCollection fc= new FormFieldCollection();

XmlSerializer s1 = new XmlSerializer(typeof(FormFieldCollection));

// explicitly specify the namespace collection to suppress default
namespace entries in the root elt:
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add( "", "" );
fc.Add(new FormField("one", "Remember the human"));
fc.Add(new FormField("two", "Adhere to the same standards of
behavior online that you follow in real life"));
fc.Add(new FormField("three", "Know where you are in cyberspace"));

// use a custom TextWriter to suppress the XML declaration

System.Console.WriteLine("\n====================== ======================\nSerialized:");
s1.Serialize(new
XmlTextWriterFormattedNoDeclaration(System.Console .Out), fc, ns);
System.Console.WriteLine("\n");

// apply a root override (not possible in code attributes on a
CollectionBase)

System.Console.WriteLine("\n====================== ======================\nSerialized
using a root override:");
XmlRootAttribute xRoot1 = new XmlRootAttribute();
xRoot1.Namespace = ""; // "urn:www.example.org";
xRoot1.ElementName = "fieldsRoot";

XmlSerializer s2 = new XmlSerializer(typeof(FormFieldCollection),
xRoot1);

s2.Serialize(new
XmlTextWriterFormattedNoDeclaration(System.Console .Out), fc, ns);
System.Console.WriteLine("\n");

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

---- end code ----

"Loui Mercieca" <lo**@gfi.com> wrote in message
news:%2***************@TK2MSFTNGP14.phx.gbl...
Hi,

I have created a class, named FormField , which basically contains two
fields, name and value. I have set the [XmlRoot(ElementName="field",
Namespace=null)] tag before the class and the field is set as an
XmlAttribute whil the name as XmlText.

In my main class, i have created an arraylist which contains a collection
of this class FormField. Basically its:

public void Add( string sName, string sValue )
{
FormField ff = new FormField( sName, sValue );
m_alFields.Add( ff );
}

The problem arise when i try to serialise this collection. For some
reason, none of the fields are present, only the root element is. The
code i use is:

XmlSerializer serializer = new XmlSerializer(typeof(FormFieldCollection),
new System.Type[] { typeof( FormField ) } );
StringWriter writer = new StringWriter();
serializer.Serialize( writer, this);

[note: FormFieldCollection is the main class]

The result i get is:

<?xml version= "1.0" encoding= "utf-16"?>
<fieldsRoot xmlns:xsd= "http://www.w3.org/2001/XMLSchema" xmlns:xsi=
"http://www.w3.org/2001/XMLSchema-instance" />

Whilst the result i want is:

<?xml version= "1.0" encoding= "utf-16"?>
<fieldsRoot>
<field name = [name]>[value]</field>
</fieldsRoot>

Furthermore is there a way, to ommit the default namespaces?

Thanks in advance.


Nov 12 '05 #3
try [XmlType("field")]
-D

"Loui Mercieca" <lo**@gfi.com> wrote in message
news:eL**************@TK2MSFTNGP12.phx.gbl...
However now i face a new problem. Although i am declaring and
XmlRootAttribute i am still getting the class name as the the root. What
am i doing wrong?

Nov 12 '05 #4

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

Similar topics

4
by: Zion Zadik | last post by:
Dear all, I have a set of c# data classes which i need to fill their data from xml files. serialization looks to be the best way to accomplish this task. Since the data classes are compiled and...
5
by: Stuart Robertson | last post by:
I am trying to find a solution that will allow me to use XmlSerializer to serialize/deserialize a collection of objects where a given object is shared between two or more other objects, and not...
1
by: Bluetears76 | last post by:
Hi I have a hirachy of classes which are Message(base), then FileMessage and ChatMessage (extended) I want to serialize the objects and when i am deserizaling i dont know if i am getting...
3
by: Anthony Bouch | last post by:
Hi I've been reading using the XmlSerializer with custom collections. I've discovered that when serializing a custom collection (a class that implements ICollection, IList etc.) the...
4
by: Andy Neilson | last post by:
I've run across a strange behaviour with XmlSerializer that I'm unable to explain. I came across this while trying to use XmlSerializer to deserialize from a the details of a SoapException. This...
12
by: SJD | last post by:
I've just read Christoph Schittko's article on XmlSerializer: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnxmlnet/html/trblshtxsd.asp . . . and very informative it is too....
4
by: Steve Long | last post by:
Hello, I hope this is the right group to post this to. I'm trying to serialize a class I've written and I'd like to be able to serialze to both binary and xml formats. Binary serialization is...
0
by: William Stacey [MVP] | last post by:
Had a method that got some string info from mp3 tags in N files and serializes this class and deserializes at other side. Works ok except sometimes get chars that choke the XmlSerializer. After...
3
by: kimtherkelsen | last post by:
Hi, I want to send XML data from a server to some clients over a network connection using the TCP/IP protocol. If I send the XMLs as byte arrays I need to insert header information in the data to...
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
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
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...
1
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
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,...
1
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...
0
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...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
muto222
php
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.