Serialization

D

Dave

I'm having trouble dynamically deserializing information.

The following code is what I have. It serialises fine, the Dave
element is serialized as the Name of the element, not its value. On
Deserialize I need to store the Name of the Dave element in Variable C
and also the same for INV.

I am using serialization, but i can't deserialize the Dave value as it
will always change, so a variable in the class cannot always be of the
same name as the element.

using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Text;

[XmlRootAttribute("CMD")]
public class INVALID
{
[XmlAttribute]
public string O;
[XmlAttribute]
public string D;
public string C;
public string INV;

}

public class Run
{
public static void Main()
{
Run test = new Run();
test.SerializeMe();
//test.DeserializeStudent("Student.xml");
}

public INVALID u;
public XmlSerializer xser;
public void SerializeMe()
{
TextWriter writer = new StreamWriter("Test.xml");
u = new INVALID();
u.D = "3048";
u.O = "PC";
u.C = "Dave";
u.INV = "";

//Override C's element to display the dynamic element
name
XmlElementAttribute myElementAttribute = new
XmlElementAttribute();
myElementAttribute.ElementName = u.C ;
myElementAttribute.IsNullable = false;
u.C = "";
XmlAttributes myAttributes = new XmlAttributes();
myAttributes.XmlElements.Add(myElementAttribute);
XmlAttributeOverrides myOverrides = new
XmlAttributeOverrides();
myOverrides.Add(typeof(INVALID), "C", myAttributes);

xser= new XmlSerializer(typeof (INVALID), myOverrides);
/*
* Remove default namespaces
*/
XmlSerializerNamespaces ns = new
XmlSerializerNamespaces();
ns.Add("", "");
StringBuilder sb = new StringBuilder();
XmlTextWriterFormattedNoDeclaration tr = new
XmlTextWriterFormattedNoDeclaration(new StringWriter(sb));
tr.Formatting = Formatting.None;
//serialize
xser.Serialize(tr, u, ns);
//sb stores serialized string
Console.WriteLine(sb.ToString());

//deserialize
u = (INVALID)xser.Deserialize(new
StringReader(sb.ToString()));
Console.WriteLine("u.D = {1}, u.O = {2}, u.C =
(name):{0}, u.INV =
(name):{3}", u.C, u.D, u.O, u.INV);
while(true)
{}
}

public class XmlTextWriterFormattedNoDeclaration :
System.Xml.XmlTextWriter
{
public XmlTextWriterFormattedNoDeclaration(
System.IO.TextWriter w) :
base(w)
{
Formatting= System.Xml.Formatting.Indented;
}
public override void WriteStartDocument() { }
}
}
 
D

Dave

Don't worry everyone i have fixed it....

Added an eventhandler to it to deal with unknownattributes which seems
to pick my problem up allowing me to get round it...

thanks for all of your help.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top