Mar*_*ark 2 xml t-sql sql-server
我在 TSQL 中构建了一些 XML。
declare @requestXML xml
set @requestXML = (
select @dataXML
for xml raw ('rtEvent')
Run Code Online (Sandbox Code Playgroud)
我现在拥有的一般输出遵循与此类似的模式:
<rtEvent>
<ctx>
.....
</ctx>
</rtEvent>
Run Code Online (Sandbox Code Playgroud)
我现在想做的是向 rtEvent 根元素节点添加一些属性和值,但我不确定如何实现它。
我查看了 XML 对象的 Modify 方法并观察了插入、替换值和删除操作,但似乎无法弄清楚如何使用它们中的任何一个来实现我所追求的结果。
基本上,我希望能够修改根节点以反映以下内容:
<rtEvent type="customType" email="someaddress@domain.com"
origin="eCommerce" wishedChannel="0" externalId="5515">
<ctx>
...
</ctx>
</rtEvent>
Run Code Online (Sandbox Code Playgroud)
我应该使用文档化的 XML.Modify 还是有更好的方法?应该怎么做?
更好地使用FOR XML PATH
,它允许您根据需要指定命名和别名:
SELECT 'SomeContext' AS [ctx]
FOR XML PATH('rtEvent')
Run Code Online (Sandbox Code Playgroud)
这将返回:
<rtEvent>
<ctx>SomeContext</ctx>
</rtEvent>
Run Code Online (Sandbox Code Playgroud)
但有了正确的属性,你会得到这样的结果:
SELECT 'customType' AS [@type]
,'someaddress@domain.com' AS [@email]
,'eCommerce' AS [@origin]
,0 AS [@wishedChannel]
,5515 AS [@externalId]
,'SomeContext' AS [ctx]
FOR XML PATH('rtEvent')
Run Code Online (Sandbox Code Playgroud)
结果
<rtEvent type="customType" email="someaddress@domain.com" origin="eCommerce" wishedChannel="0" externalId="5515">
<ctx>SomeContext</ctx>
</rtEvent>
Run Code Online (Sandbox Code Playgroud)
以防万一您想查看修改方法的方法:
DECLARE @requestXML XML = '<rtEvent><ctx>...</ctx></rtEvent>'
SET @requestXML.modify(
'insert
(
attribute type {"customeType"},
attribute email {"someaddress@domain.com"},
attribute origin {"eCommerce"},
attribute wishedChannel {"0"},
attribute externalId {"5515"}
)
into (/rtEvent)[1]')
SELECT @requestXML
Run Code Online (Sandbox Code Playgroud)
它返回这个:
<rtEvent type="customeType" email="someaddress@domain.com" origin="eCommerce" wishedChannel="0" externalId="5515">
<ctx>...</ctx>
</rtEvent>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4397 次 |
最近记录: |