如何使用 XQuery 更新 XML 变量中的属性值?

How can I use XQuery to update an attribute value in an XML variable?

正在尝试更新变量中包含的 XML 中的一个属性:

set @x.modify('declare namespace abc="http://abcsystems.com/";
replace value of
(/abc:App/abc:Client/abc:Addresses/abc:PostalAddress)[@AddressLine1] with "555 Service Rd."')

尝试在 @AddressLine1[1] 上使用和不使用下标。

这会引发错误:

Msg 2337, Level 16, State 1, Line 8
XQuery [modify()]: The target of 'replace' must be at most one node, found 'element(abc{http://abcsystems.com/}:PostalAddress,xdt:untyped) *'

整个XML中只有一个PostalAddress元素。错误告诉我什么?

没有实际的 XML 这是盲目的,但您可能正在寻找这个:

set @x.modify('declare namespace abc="http://abcsystems.com/";
replace value of
(/abc:App/abc:Client/abc:Addresses/abc:PostalAddress/@AddressLine1)[1] with "555 Service Rd."')

(xpath here)[1]通常用于执行单个节点

更新:工作示例

declare @x xml=
N'<abc:App xmlns:abc="http://abcsystems.com/">
  <abc:Client>
    <abc:Addresses>
      <abc:PostalAddress AddressLine1="test" />
    </abc:Addresses>
  </abc:Client>
</abc:App>';

set @x.modify('declare namespace abc="http://abcsystems.com/";
replace value of
(/abc:App/abc:Client/abc:Addresses/abc:PostalAddress/@AddressLine1)[1] 
with "555 Service Rd."');

select @x;

结果

<abc:App xmlns:abc="http://abcsystems.com/">
  <abc:Client>
    <abc:Addresses>
      <abc:PostalAddress AddressLine1="555 Service Rd." />
    </abc:Addresses>
  </abc:Client>
</abc:App>