我尝试将元素<Visible>
重命名为<IsVisible>
,但此SELECT返回不带子元素的Visible元素,如何使用UserId和RoleId元素获得Visible?
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(N'let $nd:=(//*[local-name()="Visible"])[1]
return
<IsVisible> {$nd/@*}
{$nd/text()}
</IsVisible>
')
答案 0 :(得分:0)
试试这个。
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(N'let $nd:=(//*[local-name()="Visible"])[1]
return
<IsVisible> {$nd/@*}
{$nd/*}
</IsVisible>
')
答案 1 :(得分:0)
您可以使用XQuery(FLWOR)或简单替换
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>';
- Works,但会重新组织您的命名空间声明
WITH XMLNAMESPACES('http://www.w3.org/2001/XMLSchema' AS xsd
,'http://www.w3.org/2001/XMLSchema-instance' AS xsi)
SELECT @xml.query(N'<Root>
{
for $nd in /Root/*
return
if(local-name($nd)!="Visible") then
$nd
else
<IsVisible>{$nd/@*}
{$nd/*}
</IsVisible>
}
</Root>
');
- 这里可能更容易
SELECT CAST(
REPLACE(REPLACE(
CAST(@xml AS NVARCHAR(MAX))
,'<Visible ','<IsVisible ')
,'</Visible>','</IsVisible>')
AS XML)