Can't call WriteXml on a class implementing IXmlSerializable

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Maybe I'm trying to do things in a counter fashion. I created a class
implementing the System.Xml.XmlSerialization.IXmlSerializable interface. When
trying to compile code that explicitely calls my class's WriteXml method, the
compiler tells me that the class doesn't have such a method.

I'm using Visual Studio 2005 Beta 2 and was trying to do this with either
..NET 2.0 or .NETCF 2.0. Neither worked.

Any help on this ? Here is some sample code that doesn't compile (I get an
error: 'WindowsApplication1.Class1' does not contain a definition for
'WriteXml'):

using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.IO;

namespace WindowsApplication1
{
public class Class1 : IXmlSerializable
{
XmlSchema IXmlSerializable.GetSchema() {
return null;
}

void IXmlSerializable.ReadXml(XmlReader reader) {
reader.ReadStartElement("MyClass");
reader.ReadEndElement();
}

void IXmlSerializable.WriteXml(XmlWriter writer) {
writer.WriteStartElement("MyClass");
writer.WriteEndElement();
}
}

static class Program
{
[STAThread]
static void Main()
{
Class1 test;
TextWriter writer = new StreamWriter("test.xml");
XmlTextWriter w = new XmlTextWriter(writer);
w.WriteStartDocument();
w.WriteStartElement("Tests");
test.WriteXml(w);
}
}
}
 
You've created an explicit interface implementation by prefixing the method
name with the interface name. Either remove the interface name from the
method definition or cast the object to IXmlSerializable then call the method.

DC
 
Ah that makes sense now! Looks like I missed this subtlety when checking the
C# docs. Thanks.
 
Back
Top