You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

构建带分页Cookie的Fetch XML时遇System.FormatException问题求助

解决Fetch XML分页Cookie拼接时的FormatException索引错误

看起来你在手动拼接带分页属性的Fetch XML时遇到了字符串格式化问题,这个System.FormatException通常是XML结构语法错误(比如引号不闭合、特殊字符未转义)或者拼接逻辑漏洞导致的。我来帮你梳理问题点和修复方案:

常见问题原因

  1. 手动拼接的语法漏洞:用分散的字符串片段拼接很容易出现引号不匹配、属性值未正确插入的问题,比如page和paging-cookie的属性值没有正确闭合引号,导致XML解析时触发索引错误。
  2. 分页Cookie未转义:paging-cookie的值本身是一段XML字符串,直接插入会和外层Fetch XML的标签冲突,必须先转义特殊字符(<、>、"等)。
  3. XML结构不完整:你代码里的order a...是截断状态,不完整的标签也会导致解析时出错。

修复方案:用格式化字符串替代手动拼接

推荐使用String.Format或者C# 6+的字符串插值来构建Fetch XML,这样更清晰且不易出错。具体步骤如下:

1. 准备分页参数

确保你有当前页码(比如currentPage)和上一页返回的分页Cookie(已经转义后的字符串,比如escapedPagingCookie)。如果是从RetrieveMultipleResponse中获取的PagingCookie,它本身已经是转义后的格式,可以直接使用。

2. 构建合法的Fetch XML

示例代码(使用String.Format):

int currentPage = 2; // 假设当前是第2页
string escapedPagingCookie = "&lt;cookie page=\"1\"&gt;&lt;contactid last=\"7a1b9c8d-1234-5678-90ab-cdef01234567\" first=\"1a2b3c4d-5678-90ab-cdef-0123456789ab\" /&gt;&lt;/cookie&gt;";

string fetchXml = string.Format(@"
<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false' count='1' page='{0}' paging-cookie='{1}'>
  <entity name='contact'>
    <attribute name='fullname' />
    <attribute name='donotbulkemail' />
    <order attribute='fullname' descending='false' /> <!-- 补全你的排序逻辑 -->
    <!-- 可按需添加filter等其他节点 -->
  </entity>
</fetch>", currentPage, escapedPagingCookie);

如果使用C# 6+的字符串插值,代码会更简洁:

string fetchXml = $@"
<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false' count='1' page='{currentPage}' paging-cookie='{escapedPagingCookie}'>
  <entity name='contact'>
    <attribute name='fullname' />
    <attribute name='donotbulkemail' />
    <order attribute='fullname' descending='false' />
  </entity>
</fetch>";

3. 关键注意事项

  • 引号一致性:外层Fetch XML的属性用单引号,分页Cookie内部的属性用双引号(或者相反),避免嵌套引号冲突。
  • 分页Cookie转义:如果你的分页Cookie是原始XML(未转义),需要先使用System.Security.SecurityElement.Escape()方法转义后再插入:
    string rawPagingCookie = "<cookie page=\"1\"><contactid last=\"...\" first=\"...\" /></cookie>";
    string escapedPagingCookie = System.Security.SecurityElement.Escape(rawPagingCookie);
    
  • XML结构完整性:确保所有标签都正确闭合,比如排序节点<order>要写完整,不能截断。

验证XML合法性

你可以把生成的Fetch XML复制到Dynamics 365的Advanced Find中导出验证,或者用在线XML校验工具检查结构是否合法,提前排查语法错误。

内容的提问来源于stack exchange,提问作者teedubya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:59:22