强制WCF代理生成别名前缀

时间:2010-06-11 05:47:34

标签: c# wcf xml-serialization

为了符合客户端架构,我一直在尝试生成一个WCF客户端代理,该代理能够序列化到具有如下所示的根节点的结构:

<quote:request
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:quote="https://foo.com/services/schema/1.2/car_quote">

经过一些阅读,我很幸运通过使用XmlNameSpaceDeclarations和XmlSerializerNamespaces来更新代理以包含所需的'quote'命名空间

[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public partial class request
{
    [XmlNamespaceDeclarations()]
    public XmlSerializerNamespaces xmlsn
    {
        get
        {
            XmlSerializerNamespaces xsn = new XmlSerializerNamespaces();
            xsn.Add("quote", "https://foo.com/services/schema/1.2/car_quote");
            return xsn;
        }
        set
        {
            //Just provide an empty setter. 
        }
    }
    ...

提供:

<request
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:quote="https://foo.com/services/schema/1.2/car_quote">

但是我对如何生成quote:request元素感到难过。

环境:ASP.NET 3.5

1 个答案:

答案 0 :(得分:1)

如果没有一些WSDL来生成代理,我无法真正重现你的情况,但如果添加XmlRoot属性,序列化位对我有效。

using System.Xml.Serialization;

[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[XmlRoot(Namespace="https://foo.com/services/schema/1.2/car_quote")]
public partial class request
{
    get 
    {
        [XmlNamespaceDeclarations()]
        public XmlSerializerNamespaces xmlsn
        {
            XmlSerializerNamespaces xsn = new XmlSerializerNamespaces();
            xsn.Add("quote", "https://foo.com/services/schema/1.2/car_quote");
            return xsn;
        }
    } 
    set { }
}