How to delete an attribute from an XML variable in sql server 2008?

巧了我就是萌 提交于 2019-11-29 14:02:38

I can't seem to find an easy way to do this - but the real question remains: why do you want to remove the namespace?? Using the WITH XMLNAMESPACES ... construct, you can easily make use of the namespaces.

Instead of putting a lot of effort in getting rid of it - learn about XML namespaces and start using them!

You can quite easily use that XML namespace in your queries:

;WITH XMLNAMESPACES (DEFAULT 'http://cp.com/rules/client' )
SELECT
    XmlDocument.value('(/clue_personal_auto/admin/report_usage)[1]', 'varchar(25)')
FROM XML
WHERE ID = 357

and be happy with it - no need to artificially remove xmlns= declarations anymore!

You need to use WITH xmlnamespaces, otherwise "/clue_personal_auto" does not match the NAMESPACED clue_personal_auto xmlns="..." node.

Not only that, you cannot actually remove a namespace since it is not a normal attribute.

Example of removing a regular attribute

declare @xml table (xmlid int, xmldocument xml)
insert @xml select 357, '
<clue_personal_auto xmlns="http://cp.com/rules/client" otherattrib="x">
  <admin>
     <receipt_date>03/16/2011</receipt_date>
     <date_request_ordered>03/16/2011</date_request_ordered>
     <report_usage>Personal</report_usage>
  </admin>
</clue_personal_auto>'

;WITH XMLNAMESPACES ('http://cp.com/rules/client' as ns)
UPDATE @XML
SET XmlDocument.modify('delete  (/ns:clue_personal_auto/@otherattrib)[1]')
WHERE xmlid = 357

select * from @xml
UPDATE XML
  SET CONVERT(XML, REPLACE(CONVERT(NVARCHAR(MAX), XmlDocument), N' xmlns=...'))
WHERE ID = 357
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!