在服务堆栈中发送xml数组

时间:2012-08-28 10:17:58

标签: c# servicestack

我目前正在使用ServiceStack执行以下操作,将一些xml发回服务器:

<Server xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <UserName>Bob</UserName>
    <UserGroups xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
       <d3p1:string>History</d3p1:string>
       <d3p1:string>Geography</d3p1:string>
     </UserGroups>
</Server>

上述工作,但我如何做到:

<Server xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <UserName>Bob</UserName>
    <UserGroups>
       <UserGroup>History</UserGroup>
       <UserGroup>Geography</UserGroup>
     </UserGroups>
</Server>

我试过了:

[CollectionDataContract(ItemName = "UserGroup")]
public partial class ArrayOfStringUserGroup : List<string>
{
    public ArrayOfStringUserGroup()
    {
    }

    public ArrayOfStringUserGroup(IEnumerable<string> collection) : base(collection) { }
    public ArrayOfStringUserGroup(params string[] args) : base(args) { }
}

我在帖子中的dto中有以下内容:

  [DataMember(Name = "UserGroups", Order = 3)]
  public ArrayOfStringUserGroup UserGroups { get; set; }

但我将UserGroups作为UserGroupDto的空数组。

2 个答案:

答案 0 :(得分:1)

这正是你想要的。

Server s = new Server();
s.UserName = "Bob";
s.UserGroups = new List<string>();
s.UserGroups.Add("History");
s.UserGroups.Add("Geography");


StringWriter stream = new StringWriter();
XmlWriter writer = 
            XmlTextWriter.Create(
              stream,
              new XmlWriterSettings() { OmitXmlDeclaration = true,Indent = true }
            );

XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("i", "http://www.w3.org/2001/XMLSchema-instance");

XmlSerializer xml = new XmlSerializer(typeof(Server));
xml.Serialize(writer,s,ns);

var xmlString = stream.ToString();

public class Server
{
    public string UserName;
    [XmlArrayItem("UserGroup")]
    public List<string> UserGroups;
}

答案 1 :(得分:0)

您是否只想删除冗余/重复的XML命名空间?

如果是这样,您应该确保所有DTO类型共享相同的单个命名空间,如果您想要从默认命名空间更改它Config.WsdlServiceNamespace,那么该命名空间应与http://schemas.servicestack.net/types匹配。

这可以通过使用通常在DTO项目的AssemblyInfo.cs文件中定义的[assembly:ContractNamespace]属性轻松完成,以下是在ServiceStack.Examples项目中完成此操作的方法:

[assembly: ContractNamespace("http://schemas.servicestack.net/types",
           ClrNamespace = "ServiceStack.Examples.ServiceModel.Operations")]
[assembly: ContractNamespace("http://schemas.servicestack.net/types",
           ClrNamespace = "ServiceStack.Examples.ServiceModel.Types")]

取自ServiceStack的SOAP Support wiki page