Dave

Dave

  • NA
  • 161
  • 0

Xml Serialization

Jun 14 2009 3:39 AM
Hi There,

I'm not sure which forum is best for my query, so forgive me if this does not belong here.
I'm trying to learn how to use the various XML attributes for XML serialization. I've started with the [XmlAnyElement] attribute.
The example in the documentation is as follows:

 public class XClass
{
/* Apply the XmlAnyElementAttribute to a field returning an array
of XmlElement objects. */
[XmlAnyElement]
public XmlElement[] AllElements;
}

public class Test
{
public static void Main()
{
Test t = new Test();
t.DeserializeObject("file.xml");

Console.WriteLine("\nPress any key to quit...");
Console.Read();
}

private void DeserializeObject(string filename)
{
// Create an XmlSerializer.
XmlSerializer mySerializer = new XmlSerializer(typeof(XClass));

// To read a file, a FileStream is needed.
FileStream fs = new FileStream(filename, FileMode.Open);

// Deserialize the class.
XClass x = (XClass)mySerializer.Deserialize(fs);

// Read the element names and values.
foreach (XmlElement xel in x.AllElements)
Console.WriteLine(xel.LocalName + ": " + xel.Value);
}
}

It does not matter what XML file I put in the bin/debug folder, I always get the following exception:

System.InvalidOperationException
was unhandled
  Message="There is an error in XML document (1, 2)."
  Source="System.Xml"
  StackTrace:
       at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
       at System.Xml.Serialization.XmlSerializer.Deserialize(Stream stream)
       at Test.DeserializeObject(String filename) in E:\XmlTest\XmlTest\Program.cs:line 37
       at Test.Main() in E:\XmlTest\XmlTest\Program.cs:line 22
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: System.InvalidOperationException
       Message="<Basket xmlns=''> was not expected."
       Source="3u_vys45"
       StackTrace:
            at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderXClass.Read3_XClass()
       InnerException:




I don't want to do anything tricky, like transform a webservice. I just want to see this wildcard in action. Even if with the most simple of XML files.
 
Does anyone know enough about this to assist me?
Thanks

Answers (1)