TSQL使用特殊字符发送XML

时间:2014-10-30 18:29:40

标签: xml tsql stored-procedures

我有一个简单的页面,它创建一个搜索数据的XML字符串并将其发送到我的存储过程。从那里,我解析它并做我需要做的任何事情。

问题是,我传递的其中一个值可能包含ampersand (&)符号。

这是我的XML示例:

<root>
   <locations>
      <location>
         <selectedLocation>Chandler</selectedLocation>
      </location>
   </locations>
   <areas>
      <area>
         <selectedArea>Customer Solutions</selectedArea>
      </area>
   </areas>
   <departments>
      <department>
         <selectedDepartment>Settings & Payments's</selectedDepartment>
      </department>
   </departments>
   <source />
</root>

如果&导致问题有效,我怎样才能正确传递。

我正在做一些研究,我相信CDATA仅用于做相反的事情;从数据库中拉出来。

有关如何正确传递的任何想法?

2 个答案:

答案 0 :(得分:0)

您需要像以下一样转义符号字符&&amp;

答案 1 :(得分:0)

我们基于64个字符串

-- Encode the string "Settings & Payments's " in Base64 to get "U2V0dGluZ3MgJiBQYXltZW50cydz"
SELECT Base64Encoding = CAST(N'' AS XML).value('xs:base64Binary(xs:hexBinary(sql:column("bin")))', 'VARCHAR(MAX)')
FROM (
    SELECT bin = CAST('Settings & Payments''s' AS VARBINARY(MAX))
    ) AS bin_sql_server_temp;

-- Decode the Base64-encoded string "U2V0dGluZ3MgJiBQYXltZW50cydz=" to get back "Settings & Payments's"
SELECT 
    CAST(
        CAST(N'' AS XML).value(
            'xs:base64Binary("U2V0dGluZ3MgJiBQYXltZW50cydz")'
          , 'VARBINARY(MAX)'
        ) 
        AS VARCHAR(MAX)
    )   ASCIIEncoding
;

那么你的xml看起来像

<root>
   <locations>
      <location>
         <selectedLocation>Chandler</selectedLocation>
      </location>
   </locations>
   <areas>
      <area>
         <selectedArea>Customer Solutions</selectedArea>
      </area>
   </areas>
   <departments>
      <department>
         <selectedDepartment>U2V0dGluZ3MgJiBQYXltZW50cydz</selectedDepartment>
      </department>
   </departments>
   <source />
</root>