我正在尝试添加属性(如果它不存在)。它应该很简单,但我是XML XPath / XQuery /等的新手,请原谅我的无知。
我希望能够传递XML数据并对其进行修改......
ALTER FUNCTION [dbo].[ConvertXmlData](@xmlData XML)
RETURNS XML
AS
BEGIN
RETURN @xmlData.<something here>
END
如果我传递的数据如下:
<something>
this is sample data <xxx id="1"/> and <xxx id="2" runat="server" />. More <yyy id="3" />
</something>
我想
<something>
this is sample data <xxx id="1" runat="server" /> and <xxx id="2" runat="server" />. More <yyy id="3" />
</something>
而不是:
<something>
this is sample data <xxx id="1" runat="server" /> and <xxx id="2" runat="server" runat="server"/>. More <yyy id="3" />
</something>
答案 0 :(得分:3)
你可以做到
SET @xmlData.modify('insert attribute runat { "server" } into descendant::xxx[not(@runat)][1]');
但是这只会更改没有runat属性的第一个xxx
后代,至少在SQL Server 2005中,您一次只能修改一个节点。
将上述内容与WHILE结合起来可能会有所帮助。
WHILE @xmlData.exist('descendant::xxx[not(@runat)]') = 1
BEGIN
SET @xmlData.modify('insert attribute runat { "server" } into descendant::xxx[not(@runat)][1]');
END
我无法访问SQL Server 2008 R2,但我认为修改仍然一次只限于一个节点,因此您可以尝试
ALTER FUNCTION [dbo].[ConvertXmlData](@xmlData XML)
RETURNS XML
AS
BEGIN
WHILE @xmlData.exist('descendant::xxx[not(@runat)]') = 1
BEGIN
SET @xmlData.modify('insert attribute runat { "server" } into descendant::xxx[not(@runat)][1]');
END
RETURN @xmlData
END