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. 3 4468
> 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.
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.
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? This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
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...
|
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...
|
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...
|
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...
|
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...
|
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....
|
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...
|
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...
|
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...
|
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...
|
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...
|
by: ryjfgjl |
last post by:
ExcelToDatabase: batch import excel into database automatically...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, we are pleased to welcome back...
|
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...
|
by: jfyes |
last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
|
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: Defcon1945 |
last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
|
by: Shællîpôpï 09 |
last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
| |