【问题标题】:WCF: XmlSerialization attribute ignored for the root elementWCF:根元素忽略 XmlSerialization 属性
【发布时间】:2011-10-18 17:25:59
【问题描述】:

我正在开发一个 RESTful WCF 服务,它返回由 XML 序列化程序(与 DataContract 序列化程序相反)生成的 XML。

虽然大多数对象的格式都正确,但返回的根元素似乎忽略了我的 XML 序列化属性。

例如,资源/accounts/ 返回我的AccountList 类的XML 序列化表示(它本身是我自己的ObjectList<T> 类的子类,它有一些应该序列化的属性)。但是我没有得到我想要的结果。

这是我的代码:

[XmlRoot("accounts")]
public class AccountList : ObjectList<Account> {
}

public class ObjectList<T> : List<T> {
    [XmlAttribute("foo")]
    public Int32 FooProperty { get; set; }
}

[OperationContract]
[WebGet(UriTemplate="/accounts")]
public AccountList GetAccounts() {
    return new AccountList() {
        new Account("bilbo baggins"),
        new Account("steve ballmer")
    };
}

这就是网络服务返回的内容:

<arrayOfAccount>
    <Account>
        <name>biblo baggins</name>
    </Account>
    <Account>
        <name>steve ballmer</name>
    </Account>
</arrayOfAccount>

所以主要问题是我想要的 AccountList 类的序列化被忽略了,我也想知道如何获取它,所以“Account”是小写的,就像“name”属性一样(我使用 [ XmlElement("name")] 在这些属性上,它工作正常。

谢谢!

【问题讨论】:

    标签: xml wcf serialization xml-serialization


    【解决方案1】:

    不是 100% 确定这会起作用,但请尝试将以下属性添加到方法中:

    [return:XmlArray("accounts")]
    [return:XmlArrayItem("account")]
    

    更新:

    由于 [return:*] 属性没有被拾取,上述方法不起作用。两个可行的选项:

    您可以让 AccountList 包含一个列表,并在其中使用 [XmlElement("account")],如下所示:

    [XmlRoot("accounts")]
    public class AccountList : ObjectList<Account> {
        [XmlElement("account")]
        public List<Account> Accounts { get; set; }
    }
    
    public class ObjectList<T> {//: List<T> {
        [XmlAttribute("foo")]
        public Int32 FooProperty { get; set; }
    }
    

    或者,如果您不介意改变响应 xml,您可以添加一个包装类并使用 [XmlArray] 和 [XmlarrayItem],如前所述:

    [XmlRoot("response")]
    public class GetAccountResponse {
      [XmlArray("accounts"), XmlArrayItem("account")]
      public AccountList Accounts { get; set; }
    }
    

    【讨论】:

    • 是的,似乎 [return:*] 属性没有被拾取,太糟糕了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-08
    • 2014-03-21
    • 1970-01-01
    • 2010-10-01
    • 2014-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多