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

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 4474
> 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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have 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
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,...
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,...

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.