如何使协定对象模型等效于我需要的响应 XML 在 WCF 中的外观



我觉得我已经做了很多次了,但似乎我必须跳过太多的箍,我想知道是否有更简单的方法。

我正在使用WCF来构建API(REST和SOAP端点)。我正在构建我希望 XML 响应从我的一个调用中的样子,并且我想知道获取其等效对象模型(数据协定)的最简单方法。

下面是一个示例 XML 请求,其中 GetSectionInvitesResponse 是应从 API 调用返回的顶级协定。

<GetSectionInvitesResponse>
 <UserID></UserID>
     <OrganizationInvites>
            <SectionInvites>
        <SectionSubscriber>
            <Section>
                <ID></ID>
                <Name></Name>
                <Description></Description>
                <Descriptor></Descriptor>
                <ParentID></ParentID>
            </Section>
            <SectionSubscriberID>
        </SectionSubscriber>
        <SectionSubscriber>
            <Section>
                <ID></ID>
                <Name></Name>
                <Description></Description>
                <Descriptor></Descriptor>
                <ParentID></ParentID>
            </Section>
            <SectionSubscriberID>
        </SectionSubscriber>
    </SectionInvites>
 </OrganizationInvites>
 <OrganizationInvites>
            <SectionInvites>
        <SectionSubscriber>
            <Section>
                <ID></ID>
                <Name></Name>
                <Description></Description>
                <Descriptor></Descriptor>
                <ParentID></ParentID>
            </Section>
            <SectionSubscriberID>
        </SectionSubscriber>
        <SectionSubscriber>
            <Section>
                <ID></ID>
                <Name></Name>
                <Description></Description>
                <Descriptor></Descriptor>
                <ParentID></ParentID>
            </Section>
            <SectionSubscriberID>
        </SectionSubscriber>
        <SectionSubscriber>
            <Section>
                <ID></ID>
                <Name></Name>
                <Description></Description>
                <Descriptor></Descriptor>
                <ParentID></ParentID>
            </Section>
            <SectionSubscriberID>
        </SectionSubscriber>
    </SectionInvites>
 </OrganizationInvites>
</GetSectionInvitesResponse>

编辑因为我在最初的帖子中不够清楚,所以我想更清楚地说明我的目标是从这个问题中获得什么。

我想知道在遵循上面显示的相同 XML 模式的同时,以最少的重复代码通过 SOAP 和 REST 公开它的最佳方法?

理论上你可以:

  1. 将示例 xml 粘贴到收藏夹的 xml 编辑器中
  2. 让编辑器自动生成 xml 架构。在Visual Studio中,它的XML>Generate Schema。例如InvitesResponse.xsd .
  3. 从命令提示符运行svcutil /dconly InvitesResponse.xsd /language:C#以创建数据协定文件。

出于好奇,我经历了这些步骤并发现:

  1. <SectionSubscriberID> 未在 XML 中正确关闭。
  2. 数据合同序列化程序不允许以您当前定义节点序列的方式进行节点序列。

svcutil 输出:

错误:命名空间"中的类型"获取部分邀请响应"不能 洋。元素"组织邀请"上的"maxHappen"必须为 1。 c 挂起架构,以便类型可以映射到数据协定 类型或使用 ImportXmlType 或使用其他序列化程序。

因此,我找到了数据合同模式参考,该参考指出在复杂类型中必须具有maxOccurs = 1。

如果要保留数据合同序列化程序而不切换到 XmlSerializer,则可能必须更改架构...如果您刚刚开始编码,您也会发现这一点。

正是在这一点上,@John桑德斯的智慧开始发挥作用,我停了下来。

最新更新