|
|
Comments and Discussions
|
|
 |

|
<Hi,
I can able to add the CDATA section inside the xml string but when i go to serialize it, it is converting the opening "<" to < which does not understand by the server as
for C++ (Xerces)and java(jaxb) doing it correctly.
The request string with CDATA before serializing is as
<body><bodystring><![CDATA[<xml version="1.0" encoding="utf-8">GroupMember]]></bodystring></body>
The request String after passing to XMLSerializer is as follows, which change the CDATA node tag which leads to DOM parsing exception.
<body><bodystring><![CDATA[<?xml version="1.0" encoding="utf-8"?><InitTypeByNamesInput xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://abc.com/Schemas/Internal/Core/2006-03/Types"><typeNames>GroupMember</typeNames></InitTypeByNamesInput>]]></bodystring></body>
Can anybody help me how i can preserve the <![CDATA] node as it is so that my server can understand the request?
Thanks in advance.
Sangram.]]></bodystring></body>
|
|
|
|

|
Hi ,
using the same teqniue i tried serialzing a variable of System.Windows.Fomrs.Button class. But it throws an error-
Error reflecting System.Windows.Froms.Button
Please tell me how to do this
Thanks
ankur
Ankur Agarwal
|
|
|
|

|
I have just started using 2.0 and it seems to have enhanced the handling of enumerators. Do you plan to upgrade?
|
|
|
|

|
is it possible to serialize xml comments, too? Because i want to convert one file to xml. the source file includes comments, and after i convert them, it would be cool if they would be present as xml comments
|
|
|
|

|
Hi,
I am working on a C# application that allows the user to draw a diagram and save it in XML format.
The following line,
[XmlElement(ElementName = "hello")],
allows me to assign a particular string as an Element name.
But I want the element name to be equal to a variable, that gets assigned a string value when I save the diagram.
So, I was wondering if there is any way that I can assign the variable name to 'ElementName' ?
Please let me know.
Thanks,
Snehal
|
|
|
|

|
I have a bit of a issue with the class that I need to serialize... can anybody help?
public class Bane
{
///
/// Navnet på banen
///
public string navn;
///
/// Størrelsen på hele banen
///
//[NonSerialized]
const int WIDTH = 700;
//[NonSerialized]
const int HEIGHT = 440;
///
/// Indeholder den retangel som er banens ydre kant
///
//[NonSerialized]
public GraphicsPath gp;
///
/// Startretningen for slangen
///
public Retning startRetning;
///
/// Startpunktet for slangen
///
public Point startPoint;
///
/// Skal indeholde Point arrays for hver sæt a vægge.
///
public Point[][] vaegge;
//[NonSerialized]
public PointStatus[,] net;
public Bane(Point[][] vaegge, Point startPoint, Retning startRetning, string navn)
{
this.gp = new GraphicsPath();
this.gp.AddRectangle(new Rectangle(0,0,WIDTH,HEIGHT));
this.navn = navn;
this.startRetning = startRetning;
this.startPoint = startPoint;
this.vaegge = vaegge;
ResetBane();
}
I've tried several solutions, but none seems to be able to handle the double array or my Enum 'Retning'
|
|
|
|

|
iam trying to deserialize a xml file into an array of class objeccts in c#
here is thecodei use:
using System;
using System.Xml.Serialization;
using System.Xml;
using System.IO;
using System.Diagnostics;
[XmlRoot("Mapping")]
public class Mapping
{
[XmlElement("tag")]
public string tag;
[XmlElement("url")]
public string url;
public Mapping(){}
public Mapping(string tag,string url)
{
this.tag=tag;
this.url=url;
}
}
public class Reader
{
public static void Main(string[] arg)
{
// Create an instance of the XmlSerializer class of type Contact array
XmlSerializer x = new XmlSerializer( typeof(Mapping[]) );
// Read the XML file if it exists ---
FileStream fs = null;
Mapping[] mappings=null;
try
{
fs = new FileStream( "mappingfile.xml", FileMode.Open );
// Deserialize the content of the XML file to a Contact array
// utilizing XMLReader
XmlReader reader = new XmlTextReader(fs);
mappings = (Mapping[]) x.Deserialize( reader );
}
catch( FileNotFoundException )
{
Console.WriteLine("The file does not exist!!");
}
finally
{
if(mappings != null)
{
for(int i=0;i<mappings.Length;i++)
{
if(mappings[i].tag == "213")
{
string urlRetrieved = mappings[i].url;
ProcessStartInfo info = new ProcessStartInfo(urlRetrieved);
info.Verb="open";
Process.Start(info);
}
}
}
if ( fs != null ) fs.Close();
}
}
}
Here the xml file:
<Mapping xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
213
www.cs.purdue.edu
</Mapping>
i get an exception InvalidOperationExcpetion frm the line
"mappings = (Mapping[]) x.Deserialize( reader );
saying that there was an error in teh xml document
can someone tell me what iam doing wrong?
thanks
sumaira
|
|
|
|

|
I have array of XmlSchema (XmlSchema[]), plz see below:
I could able to serialize using XmlSerializer as below:
----
----
XmlSerializer theSerializer = new XmlSerializer(typeof(XmlSchema[]));
TextWriter writer = new StreamWriter("SchemaCollection.xml");
theSerializer.Serialize(writer, xmlSchemaArray); //XmlSchema[] object
writer.Close();
However, i could not able to de-serialize this. I tried with following code:
FileStream fs = new FileStream("SchemaCollection.xml", FileMode.Open);
XmlReader reader = new XmlTextReader(fs);
if (theSerializer.CanDeserialize(reader))
{
xmlSchemaArray = (XmlSchema[])theSerializer.Deserialize(reader);
}
reader.Close();
This above code is not working. The XmlSchemaArray is blank!!!
Can any one tell me what is going wrong??? I already spent my whole weekend with this problem. Please help me..
|
|
|
|

|
I can't seem to find any examples of how to serialize objects that have user-defined objects within them. For example:
public class BankAccount
{
public int accountNumber;
public float balance;
}
public class Person
{
public int id;
public string name;
public BankAccount account;
}
Now, what XML tags ([XmlAttribute] / [XmlElement]) do I need to add to these classes in order to be able to serialize Person objects?
|
|
|
|

|
Use XmlElement and XmlAttribute anywhere you want. I recomment using XmlElement on non-intrinsic properties (where as you put XmlRoot on the class itself, but the prop attribute overrides). Basically, you do whatever you want. The XmlSerialier (or any serializer that's written correctly) will serialize an entire object graph, as serializers are supposed to.
Here's what I recommend:
[XmlRoot("bankAccount")]
public class BankAccount
{
[XmlAttribute("accountNumber")]
public int accountNumber;
[XmlAttribute("balance")]
public float balance;
}
[XmlRoot("person")]
public class Person
{
[XmlAttribute("id")]
public int id;
[XmlAttribute("name")]
public string name;
[XmlElement("account")]
public BankAccount account;
}
Reminiscent of my younger years...
10 LOAD "SCISSORS"
20 RUN
|
|
|
|

|
This is what I've been trying so far:
----------------------------------------
[XmlRootAttribute(Namespace="Bank", ElementName = "BankAccount", IsNullable = false)]
public class BankAccount
{
[XmlElement(DataType = "int")]
public int accountNumber;
[XmlElement(DataType = "float")]
public float balance;
public serializeMe(StreamWriter writer)
{
XmlSerializer xmls = new XmlSerializer(typeof(BankAccount));
xmls.Serialize(writer, this);
}
}
public class Person
{
[XmlElement(DataType = "int")]
public int id;
[XmlElement(DataType = "string")]
public string name;
[ ??? ]
public BankAccount account;
public serializeMe(StreamWriter writer)
{
XmlSerializer xmls = new XmlSerializer(typeof(Person));
xmls.Serialize(writer, this);
}
}
----------------------------------------
And, with this, everything has worked fine, except for BankAccount within the Person class.
In theory, if the BankAccount object is serializable, can I serialze it as an XmlElement tag? If so, what do type do I assign it as?!
I've also tried using the XmlAttribute tag for the BankAccount object, but when I serialize a Person object, nothing shows up in the serialized file.
(e.g.
[XmlAttribute("BankAccount")]
public BankAccount account;
)
I know I'm still missing something, but what is it? I'm coding blind. Please help!
|
|
|
|

|
First, don't use the DataType property in your XML attributes, especially if you're just reiterating what's already apparent: an int is an int, and a float is a float. Trust me, the system knows!
If you use the code I gave you, all should work well. I've done this many times and it is quite simple. Give it a try and, again, don't use the DataType unless you need to persist something differently that what it's type (either through intrinsic rules or inherited from the Type's XML serialization attributes) declares.
Reminiscent of my younger years...
10 LOAD "SCISSORS"
20 RUN
|
|
|
|

|
Ok, I've got everything being serialized, but now I've run into a problem with deserializing.
In the actual code I'm using, not just the simple BankAccount/Person example, I have many objects that need to be serialized. The problem seems to be that using the code given in this tutorial, each time I serialize an object, it creates a new top-level element. Now, I could put each object's XML data into a new file, but that seems silly. Given the large number of objects I have, I would like to put it all into one file. What do I need to do in order to accomplish this, given the code used in this tutorial as a starting point.
Thanks!
|
|
|
|

|
You don't have to serialize to a file. You can serialize to any Stream, including a MemoryStream. Serialize to a few of those, then read through each stream and add the content to a parent node that is a FileStrea or something (persistent to a file).
Reminiscent of my younger years...
10 LOAD "SCISSORS"
20 RUN
|
|
|
|

|
Yes, this is what I am having problems with. How do I "add the content to a parent node that is a File Stream" ? I assume I need to use something like a XmlWriter object?
|
|
|
|

|
Right. Serialize each object to a MemoryStream, then use an XmlTextReader (or do it raw) to read each MemoryStream and save it to an XmlTextWriter that uses a FileStream for persistence. There are examples in the .NET Framework SDK docs.
Reminiscent of my younger years...
10 LOAD "SCISSORS"
20 RUN
|
|
|
|

|
Ok, here's what I'm trying:
----------------------------------------------------
Stream stream = null;
MemoryStream mStream1 = new MemoryStream();
MemoryStream mStream2 = new MemoryStream();
XmlTextReader xmltr1 = null;
XmlTextReader xmltr2 = null;
XmlTextWriter xmltw = null;
StreamWriter writer = null;
if((stream = saveFileDialog.OpenFile()) != null)
{
// File stream
writer = new StreamWriter(stream);
// Collect XML data
constants.SerializeObject(mStream1);
vehicleManager.serializeVehicles(mStream2);
xmltr1 = new XmlTextReader(mStream1);
xmltr2 = new XmlTextReader(mStream2);
xmltw = new XmlTextWriter(stream,Encoding.ASCII);
xmltw.WriteStartDocument();
xmltw.WriteStartElement("Bank");
xmltw.WriteEndElement();
xmltr1.MoveToFirstAttribute();
xmltr1.Read();
xmltw.WriteRaw(xmltr1.Value);
xmltr1.MoveToNextAttribute();
xmltr1.Read();
xmltw.WriteRaw(xmltr1.Value);
xmltw.WriteEndElement();
xmltw.WriteEndDocument();
xmltw.Flush();
writer.Close();
}
.
.
.
------------------------------------------------------
I can't seem to find any specific examples in the SDK docs or elsewhere on this. Am I sort of on the right track, or not even close?
With this method, so far I seem to be running into a problem of not having a root element. That's what I thought I was creating with the WriteStartElement("Bank") call. Am I wrong?
Basically, the problem is that the memory streams each contain complete XML documents on their own, complete with headers and all. So, if I just try to smoosh them together in one file, there ends up being multiple headers and multiple top-level elements.
I assume this means that I need to use an XMLReader to parse through the XML structures in the memory streams and pluck out the elements within, then in turn, to put these elements inside a new XML structure I'm building (perhaps using WriteRaw()) using the XmlTextWriter. Does that sound correct? If so, where am, I going wrong?
Thanks for the help, by the way! It's very much appreciated.
|
|
|
|

|
First of all, did you read the documentation for XmlTextWriter.WriteStartElement()? If you had, you wouldn't even be asking me that question: never forget about reading documentation - you'll never learn if you only guess. There's even a simple example in there. You're not getting a root because you're trying to write multiple roots - I'm surprised you're not getting an exception.
Second, while are you calling XmlTextReader.MoveToNextAttribute()? You do know the difference between attributes and elements, right? You don't want attributes - you want the whole element. XmlTextReader.Value isn't good either - it only gets you the normalized text for the element - not the XML document that you want to treat as a fragment.
Since the XmlTextReader should be positioned at the root element of the serialized graph, use XmlTextReader.ReadOuterXml. Read the docs though, so that you know exactly what it does. Reading the docs (i.e., researching) is half of programming - at least.
Reminiscent of my younger years...
10 LOAD "SCISSORS"
20 RUN
|
|
|
|

|
For anyone out there actually looking for examples, here is the solution I used. I'm sure there are other ways, however.
One important thing to note is that you can't use the same XMLSerializer for serializing or deserializing different types. That is, you need a new serializer object for each object type that you are deserializing.
This is the XML file I was working with:
<xml...?>
<global>
<ObjectOfType1>
<name>blah</name>
.
.
.
</ObjectOfType1>
<ArrayOfObjectOfType2>
<ObjectOfType2>
<name>blah</name>
.
.
.
</ObjectOfType2>
<ObjectOfType2>
<name>blah</name>
.
.
.
</ObjectOfType2>
.
.
.
</ArrayOfObjectOfType2>
<global>
Now, here's the snippet that deserialized it (note that error checking and some declarations are ommitted):
fs = new FileStream(openFileDialog.FileName,FileMode.Open);
XmlTextReader xmlr = new XmlTextReader(fs);
xmlr.ReadStartElement();
// Read past first
xmlr.ReadInnerXml();
XmlSerializer xmls = new XmlSerializer(typeof(ObjectOfType1));
ObjectOfType1 o1 = (ObjectOfType1)xmls.Deserialize(xmlr);
XmlSerializer xmls2 = new XmlSerializer(typeof(ObjectOfType2[]));
(ObjectOfType2[])list.ToArray(typeof(ObjectOfType2));
ObjectOfType2[] arrayO2 = (ObjectOfType2[])xmls2.Deserialize(xmlr);
This seems to work well, albeit a little slowly. Please let me know if you find a better way.
|
|
|
|

|
If the string is of RTF type don't deserialize it . Suggestions ?
|
|
|
|

|
I am trying to figure out how to serialize an ArrayList that contains other ArrayLists. The sub arrayLists all hold the same type of object.
IE -
alist1
sublist1
myObject1
myObject2
sublist2
myObject3
myObject4
myObject5
I know how to serialize an ArrayList out, even if it has different objects in it.
Any help would be greatly appreciated!
Regards,
Aaron R>
|
|
|
|

|
You cannot serialize the ArrayList objects directly. Your class needs to implement the ICollection interface, and in your class you can have an ArrayList member variable. You need to implement an "Add" method and an "Item" property in order to be serialized. Also you must implement the ICollection methods as shown below,
Class FooList : ICollection
{
//--- list may contain list of Foo ---
private ArrayList list = new ArrayList;
//--- Implement the "Add" and "Item" methods ---
//--- Implement ICollection methods ---
}
Class Foe
{
//--- fooList is one of the member variables ---
private FooList fooList = new FooList();
//--- Implement the fooList property ---
}
Hope it helps.
Liong
|
|
|
|

|
Hi!
This article was great. I was just wondering if it's possible to serialize recursively...
Basically, I have 3 classes: directory class, a file class, and includefile class (that extends file)
The directory class has 1 arraylist to hold other directories and 1 array list to hold files and the file class has 1 arraylist to hold includefile's and 1 arraylist to hold strings.
I am having trouble getting the include file list to show up properly (directories and files are ok). I think it's because in the includefile class, I xmlinclude(gettype(file))
and in the file class, since i have a list of include files, i xmlinclude(gettype(includefile)) I think this circular definition may be causing the problem?
How should these xmlincludes be handled?
Thanks!
|
|
|
|

|
A good question! If you can email (liong_ng@yahoo.com) me your code snippet, I can try to figure it out.
|
|
|
|

|
You can if it is a tree stucture, like a directory, but if the Formatter encounters a loop (.i.e see the same object twice) an exception is thrown to the effect.
To overcome this problem with serializing object meshes i you need to have your objects implement ISerializable and override the normal but you still lose the structure.
Jan
|
|
|
|
|

|
Hi,
I'm not the author of the article but in case you have not received an answer to you question, take a look at http://www.crownwood.net. This site offers an open source C# Docking/Menu/etc. control (MagicUI) which saves and restores settings to and from xml. Even if you don't use the tool, the source is very helpful.
Craig
|
|
|
|
|

|
Hi, Thanks.
Since Font and Color do not have a default constructor, it won't work with XmlSerializer. Unfortunately, we also cannot create a class that derives from Font or Color since they are sealed.
You may have to write your own Font or Color serializer class utilizing XmlTextWriter or similar classes.
I hope it works out for you.
Liong Ng
|
|
|
|

|
why don't you do something like:
public class YourClassName
{
private Color c;
public YourClassName(){}
public YourClassName(Color c)
{
this.c = c;
}
public int MyFontColor
{
get{return this.c.ToArgb();}
set{this.c = new Color.FromArgb(value);}
}
}
|
|
|
|
 |
|
|
General News Suggestion Question Bug Answer Joke Rant Admin
|
This article shows an example on how to use XML serialization in .NET
| Type | Article |
| Licence | |
| First Posted | 26 Jul 2002 |
| Views | 184,198 |
| Bookmarked | 52 times |
|
|