如何在我的XML文件中格式化SQL,以便C#不认为查询是XML的一部分?

Jas*_*son 0 c# xml sql

我有几个查询存储在XML文件中.给我问题的条目是:

<Xiphos>
        SELECT 
      'AccountGrants', 
          cast (STUFF (SUBSTRING(b.PiiData,0,PATINDEX ('%</AccountNumber>%',b.PiiData ) ),1,24,'') as char(40) ) as Gen2accountNumber  
      ,[GrantTypeId] as GrantType-- constant always 1
      ,[GrantAmount]  as GrantedAmount
      ,[UsedAmount]
      ,[AwardedDate]
      ,[ExpirationDate]
      FROM [Xiphos].[dbo].[AccountGrants]a
      join Xiphos.dbo.Accounts b
      on a.AccountId = b.AccountId
      where b.FinancialInstitutionId =@InstitutionId
      order by Gen2accountNumber,AwardedDate;
</Xiphos>
Run Code Online (Sandbox Code Playgroud)

在其中包含" </AccountNumber>" 的查询的第3行导致我的项目无法编译,因为它认为这是格式错误的XML语句(或缺少打开的AccountNumber).

我似乎无法弄清楚如何重新格式化查询或修改我的XML,这样就不会发生这种情况.

导致问题的PiiData列如下所示:

<PiiData><AccountNumber>150</AccountNumber>
Run Code Online (Sandbox Code Playgroud)

Ode*_*ded 6

问题在于查询中的<>字符 - 它们被视为普通的XML,您需要转义它们 - 有几种方法可以做到这一点.

您可以将查询括在一个<![CDATA[]]>部分中:

<Xiphos>
  <![CDATA[
        SELECT 
      'AccountGrants', 
          cast (STUFF (SUBSTRING(b.PiiData,0,PATINDEX ('%</AccountNumber>%',b.PiiData ) ),1,24,'') as char(40) ) as Gen2accountNumber  
      ,[GrantTypeId] as GrantType-- constant always 1
      ,[GrantAmount]  as GrantedAmount
      ,[UsedAmount]
      ,[AwardedDate]
      ,[ExpirationDate]
      FROM [Xiphos].[dbo].[AccountGrants]a
      join Xiphos.dbo.Accounts b
      on a.AccountId = b.AccountId
      where b.FinancialInstitutionId =@InstitutionId
      order by Gen2accountNumber,AwardedDate;
  ]]>
</Xiphos>
Run Code Online (Sandbox Code Playgroud)

或者,通过使用它们的实体引用来逃避它们 - &lt;for <&gt;for >.