开发者

WCF serialize exception

开发者 https://www.devze.com 2023-01-11 17:57 出处:网络
I have a type MyParameter that i pass as a parameter to a wcf service [Serializable] public class MyParameter : IXmlSerializable

I have a type MyParameter that i pass as a parameter to a wcf service

[Serializable]
public class MyParameter : IXmlSerializable
{
    public string Name { get; set; }
    public string Value { get; set; }
    public string Mytype { get; set; }

    #region IXmlSerializable Members

    public System.Xml.Schema.XmlSchema GetSchema()
    {
        return null;
    }

    public void ReadXml(System.Xml.XmlReader reader)
    {
        XElement e = XElement.Parse(reader.ReadOuterXml());
        IEnumerable<XElement> i = e.Elements();
        List<XElement> l = new List<XElement>(i);
        Name = l[0].Name.ToString();
        Value = l[0].Value.ToString();
        Mytype = l[0].Attribute("type").Value.ToString();
    }

    public void WriteXml(System.Xml.XmlWriter writer)
    {
        writer.WriteStartElement(Name);
        writer.WriteAttributeString("xsi:type", Mytype);
        writer.WriteValue(Value);
        writer.WriteEndElement();
    }

    #endregion
}

the service contract looks like this:

[ServiceCon开发者_StackOverflow中文版tract]
public interface IOperation
{
[OperationContract]
void Operation(List<Data> list);

}

where data defines a data contract

[DataContract]
public class Data
{
public string Name { get; set; }
public List<MyParameter> Parameters{ get; set; }
}

when i run the service and test it i get rhe exception in readXml of MyParameter "the prefix xsi is not defined" xsi should define the namespace "http://w3.org/2001/xmlschema-instance"

How do I fix the problem?

I am very new to this so a sample code will be very helpful


You have to explicitly tell the XmlWriter what xsi maps to. Try this instead:

writer.WriteAttributeString("xsi", "type", "http://w3.org/2001/xmlschema-instance", MyType);


I'm not sure you need the IXmlSerializable. WCF tries to handle the serialization in the background without bothering you about it.

It looks like you may be missing a couple attributes on your DataContract object. Try this instead:

[DataContract]
public class Data {

[DataMember]
public string Name { get; set; }

[DataMember]
public List<string> Parameters { get; set; }

}

The [DataMember] attribute marks which properties you want WCF to automatically serialize for you.

0

精彩评论

暂无评论...
验证码 换一张
取 消