1

I have a .NET Web API project where I have a Data Transfer Object Class which I want to serialize to XML.

The class (simplified) is basically defined as follows:

[XmlType("user")]
public class PublicVisibleUserDTO
{   
    public long id { get; set; }
    public string screenname { get; set; }
}

Now, when I call a function that returns only one element, I get good and proper XML as I expect:

<user>
    <id>123</id>
    <screenname>john</screenname>
</user>

However, when I have a function that returns a collection of this Data Transfer Object I get:

<ArrayOfUser>
    <user>
        <id>123</id>
        <screenname>john</screenname>
    </user>
    <user>
        <id>124</id>
        <screenname>jane</screenname>
    </user>
</ArrayOfUser>

But what I want is:

<users>
    <user>
        <id>123</id>
        <screenname>john</screenname>
    </user>
    <user>
        <id>124</id>
        <screenname>jane</screenname>
    </user>
</users>

So basically I want the collection to be returned as "types" (users) rather than "ArrayOfType" (ArrayOfUser). How do I do this?

I have tried applying an XmlArray/XmlArrayAttribute function at the top of the class declaration, but that cannot be applied to a class definition.

4

1 回答 1

2

我找到了基于提供的 jbl链接的解决方法。(我称其为解决方法而不是解决方案,因为我无法相信没有更简单的方法可以实现这一点,但至少现在可以完成工作)。

正如链接所示,我添加了一个从 List 继承的额外类:

[XmlRoot("users")]
public class PublicVisibleUsersList : List<PublicVisibleUserDTO> { }

现在,默认情况下,在返回多个元素的控制器操作中执行 Linq 查询时,我会返回某种 IEnumberable。所以我现有的控制器动作看起来像:

    // GET api/users
    public IEnumerable<PublicVisibleUserDTO> Getusers()
    {
        var results = dbContext.Users.Where...//Entity Framework Linq query to fill data from database
        return results;
    }

但我修改了它以返回新集合类型的值:

    // GET api/users
    public PublicVisibleUsersList Getusers()
    {
        PublicVisibleUsersList myList = new PublicVisibleUsersList();
        var results = dbContext.Users.Where...//Entity Framework Linq query to fill data from database
        myList.AddRange(results); //AddRange() accepts an IEnumerable<T>, so I'm able to "convert" my results from the linq query to my newly defined list type by adding the result values to myList           
        return myList;
    }
于 2013-10-10T08:32:06.337 回答