第一個問題可以通過使用簡單的XPATH語法來回答,如下所示。
declare @x xml = '<Form title="Sample Data">
<MyProperty>1234</MyProperty>
<Employee>
<MyProperty>1234</MyProperty>
</Employee>
</Form>';
--does MyProperty exist at the root level?
declare @rootlevelvalue nvarchar(max) = (select T.c.value('(MyProperty)[1]','nvarchar(max)') from @x.nodes('/Form') T(c));
if @rootlevelvalue is not null
begin
print 'yes, it exists at the root level (value = ' + @rootlevelvalue + ')';
end
else
begin
print 'no, it does not exist at the root level'
end
而第二個問題可以用XPath的插入語法來回答。同時
declare @y xml = '<Form title="Sample Data">
<Employee>
<MyProperty>1234</MyProperty>
</Employee>
</Form>';
--does MyProperty exist at the root level?
declare @rootlevelvalue nvarchar(max) = (select T.c.value('(MyProperty)[1]','nvarchar(max)') from @y.nodes('/Form') T(c));
if @rootlevelvalue is not null
begin
print 'yes, it exists at the root level (value = ' + @rootlevelvalue + ')';
end
else
begin
print 'no, it does not exist at the root level';
set @y.modify('insert <MyProperty>99999</MyProperty>into (/Form)[1]')
print 'so we added it.';
end
select @y
一個問題請,尤其是當你不知道在哪裏,如何開始。你想先做什麼?我假設:「檢查MyProperty是否存在於XML的根級別」。閱讀有關['存在()'](https://msdn.microsoft.com/en-us/library/ms189869.aspx)方法,並嘗試實施它爲您的情況 – har07