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

MS SQL中重命名含子元素的XML元素时如何保留子元素

如何重命名XML元素并保留所有子元素与属性

嘿,我明白你的需求了——要把<Visible>改成<IsVisible>,同时还得保留它下面的UserId、RoleId子元素以及原本的属性对吧?之前的SELECT没拿到这些内容,大概率是因为你只复制了元素本身,没处理它的属性和子节点。

下面给你两种可行的T-SQL方案,按需选择:

方案一:构造新XML节点(适合查询返回结果)

这种方法通过XQuery重新构建XML结构,精准保留所有需要的内容:

DECLARE @xml XML = N'<Root xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
<FieldId>2200</FieldId> 
<Visible xsi:type="UserRole"> 
  <UserId xsi:type="CurrentUserId" /> 
  <RoleId>26</RoleId> 
</Visible> 
</Root>';

SELECT 
    @xml.query('
        <Root xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            {/Root/FieldId} <!-- 保留原FieldId元素 -->
            <IsVisible>
                {/Root/Visible/@*} <!-- 复制原Visible的所有属性(比如xsi:type) -->
                {/Root/Visible/node()} <!-- 复制原Visible下的所有子节点(包括UserId、RoleId) -->
            </IsVisible>
        </Root>
    ') AS ModifiedXml;

结果说明

执行后会返回包含完整内容的XML:

<Root xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <FieldId>2200</FieldId>
  <IsVisible xsi:type="UserRole">
    <UserId xsi:type="CurrentUserId" />
    <RoleId>26</RoleId>
  </IsVisible>
</Root>

方案二:直接修改原XML变量(适合原地更新)

如果不需要返回新结果,而是直接修改原变量里的XML,用modify()方法的rename操作更简洁:

DECLARE @xml XML = N'<Root xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
<FieldId>2200</FieldId> 
<Visible xsi:type="UserRole"> 
  <UserId xsi:type="CurrentUserId" /> 
  <RoleId>26</RoleId> 
</Visible> 
</Root>';

-- 直接重命名元素,自动保留所有属性和子元素
SET @xml.modify('
    rename node /Root/Visible to "IsVisible"
');

SELECT @xml AS ModifiedXml;

这个方法会直接把原XML中的<Visible>改成<IsVisible>,所有子元素和属性都会完整保留,非常省心。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 10:00:14