473,791 Members | 2,827 Online
Bytes | Software Development & Data Engineering Community
+ 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(Element Name="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(t ypeof(FormField Collection),
new System.Type[] { typeof( FormField ) } );
StringWriter writer = new StringWriter();
serializer.Seri alize( writer, this);

[note: FormFieldCollec tion 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 4517
> 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,

XmlSerializerNa mespaces ns = new XmlSerializerNa mespaces();
ns.Add( "", "" );
XmlSerializer s1 = new XmlSerializer(t ypeof(FormField Collection));
FormFieldCollec tion fc= new FormFieldCollec tion();
// add elements here ....
s1.Serialize(Sy stem.Console.Ou t, 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.Seri alization;

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

public FormField() {}
public FormField(strin g 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("fields Root", Namespace="", IsNullable=fals e)]
// [XmlType("fields Root", Namespace="")]
public class FormFieldCollec tion : System.Collecti ons.CollectionB ase {
public FormFieldCollec tion() {}

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 XmlTextWriterFo rmattedNoDeclar ation :
System.Xml.XmlT extWriter {
public XmlTextWriterFo rmattedNoDeclar ation (System.IO.Text Writer w) :
base(w) { Formatting= System.Xml.Form atting.Indented ;}
public override void WriteStartDocum ent () { }
}
public class TestDriver {

static void Main(string[] args) {

try {

FormFieldCollec tion fc= new FormFieldCollec tion();

XmlSerializer s1 = new XmlSerializer(t ypeof(FormField Collection));

// explicitly specify the namespace collection to suppress default
namespace entries in the root elt:
XmlSerializerNa mespaces ns = new XmlSerializerNa mespaces();
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("thre e", "Know where you are in cyberspace"));

// use a custom TextWriter to suppress the XML declaration
System.Console. WriteLine("\n== =============== =============== ============\nS erialized:");
s1.Serialize(ne w
XmlTextWriterFo rmattedNoDeclar ation(System.Co nsole.Out), fc, ns);
System.Console. WriteLine("\n") ;

// apply a root override (not possible in code attributes on a
CollectionBase)
System.Console. WriteLine("\n== =============== =============== ============\nS erialized
using a root override:");
XmlRootAttribut e xRoot1 = new XmlRootAttribut e();
xRoot1.Namespac e = ""; // "urn:www.exampl e.org";
xRoot1.ElementN ame = "fieldsRoot ";

XmlSerializer s2 = new XmlSerializer(t ypeof(FormField Collection),
xRoot1);

s2.Serialize(ne w
XmlTextWriterFo rmattedNoDeclar ation(System.Co nsole.Out), fc, ns);
System.Console. WriteLine("\n") ;

}
catch (System.Excepti on e1) {
System.Console. WriteLine("Exce ption!\n" + e1);
}
}
}
}

---- end code ----

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

I have created a class, named FormField , which basically contains two
fields, name and value. I have set the [XmlRoot(Element Name="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(t ypeof(FormField Collection),
new System.Type[] { typeof( FormField ) } );
StringWriter writer = new StringWriter();
serializer.Seri alize( writer, this);

[note: FormFieldCollec tion 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
XmlSerializerNa mespaces emptyNamespace = new XmlSerializerNa mespaces();
emptyNamespace. Add("", "");

//Declare a new XmlSerializer instance, with the type of an array of
FormField, and the default attribute.
XmlSerializer serializer = new XmlSerializer(t ypeof(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.Seri alize( writer, this.Fields,emp tyNamespace );

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

The declaration is as follows
[XmlRootAttribut e("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******** ******@TK2MSFTN GP14.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,

XmlSerializerNa mespaces ns = new XmlSerializerNa mespaces();
ns.Add( "", "" );
XmlSerializer s1 = new XmlSerializer(t ypeof(FormField Collection));
FormFieldCollec tion fc= new FormFieldCollec tion();
// add elements here ....
s1.Serialize(Sy stem.Console.Ou t, 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.Seri alization;

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

public FormField() {}
public FormField(strin g 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("fields Root", Namespace="", IsNullable=fals e)]
// [XmlType("fields Root", Namespace="")]
public class FormFieldCollec tion : System.Collecti ons.CollectionB ase {
public FormFieldCollec tion() {}

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 XmlTextWriterFo rmattedNoDeclar ation :
System.Xml.XmlT extWriter {
public XmlTextWriterFo rmattedNoDeclar ation (System.IO.Text Writer w) :
base(w) { Formatting= System.Xml.Form atting.Indented ;}
public override void WriteStartDocum ent () { }
}
public class TestDriver {

static void Main(string[] args) {

try {

FormFieldCollec tion fc= new FormFieldCollec tion();

XmlSerializer s1 = new XmlSerializer(t ypeof(FormField Collection));

// explicitly specify the namespace collection to suppress default
namespace entries in the root elt:
XmlSerializerNa mespaces ns = new XmlSerializerNa mespaces();
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("thre e", "Know where you are in cyberspace"));

// use a custom TextWriter to suppress the XML declaration

System.Console. WriteLine("\n== =============== =============== ============\nS erialized:");
s1.Serialize(ne w
XmlTextWriterFo rmattedNoDeclar ation(System.Co nsole.Out), fc, ns);
System.Console. WriteLine("\n") ;

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

System.Console. WriteLine("\n== =============== =============== ============\nS erialized
using a root override:");
XmlRootAttribut e xRoot1 = new XmlRootAttribut e();
xRoot1.Namespac e = ""; // "urn:www.exampl e.org";
xRoot1.ElementN ame = "fieldsRoot ";

XmlSerializer s2 = new XmlSerializer(t ypeof(FormField Collection),
xRoot1);

s2.Serialize(ne w
XmlTextWriterFo rmattedNoDeclar ation(System.Co nsole.Out), fc, ns);
System.Console. WriteLine("\n") ;

}
catch (System.Excepti on e1) {
System.Console. WriteLine("Exce ption!\n" + e1);
}
}
}
}

---- end code ----

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

I have created a class, named FormField , which basically contains two
fields, name and value. I have set the [XmlRoot(Element Name="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(t ypeof(FormField Collection),
new System.Type[] { typeof( FormField ) } );
StringWriter writer = new StringWriter();
serializer.Seri alize( writer, this);

[note: FormFieldCollec tion 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******** ******@TK2MSFTN GP12.phx.gbl...
However now i face a new problem. Although i am declaring and
XmlRootAttribut e 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
1632
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 i don't have control on the xml structure, I tried using the xmlAttributeOverrides class, to instruct the serializer. I was able to override the attributes for the root element, but I'm having problems understanding how to deserialize arrays.
5
5430
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 create duplicate XML representations of the shared object, but instead use IDREFs to refer to the shared object. The XML I'm trying to produce is as follows (where "href" is an IDREF): <?xml version="1.0" encoding="utf-8"?> <MyRootClass...
1
4323
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 FileMessage or ChatMessage. So how to get that object and use it I have written following code for serialization public void Send(Message message) { NetworkStream netWorkStream=null;
3
7003
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 XmlSerializer will only serialize the collection items - with the default root as ArrayofMyItems etc. My custom collection class has some additional public properties that I would like to include in the serialization above the items element array (in
4
11402
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 should have worked fine since the class in question was already being serialized and deserialized as part of a Web service interface. What I found was that by deserializing from an XmlNodeReader instead of an XmlTextReader, XML Serialization doesn't work...
12
8503
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. I, too, am getting nasty FileNotFound exceptions. I've read, and digested the article, and I think I've found a bug -- it's difficult to track, though it does happen often.
4
1993
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 working fine but when I try to instantiate an XmlSerializer object with: Dim xmls As New XmlSerializer(GetType(CLayerDefinition)) I get the following error:
0
2309
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 some digging, I found XmlSerializer chokes on 0x03 chars. It probably chokes on many others, but this one I found. It serializes ok, but chokes on deserialize on "<Field1>&#x3;</Field1>". So the questions are: 1) Why does serializer produce...
3
3303
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 distinguish the XMLs from each other in the stream of data. Is there any way to avoid this (for instance by sending SOAP telegrams))? I have tried using the XMLSerializer.Serialize(stream) to serialize the XML telegrams and send them over the...
0
9515
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
10426
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...
0
10207
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10154
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
9029
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...
0
6776
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();...
0
5430
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4109
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
2
3713
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.