我正在使用將引數的 XML 檔案存盤為列的第三方軟體。我正在嘗試撰寫一個 SQL-Server 腳本來替換下面 XML 中的電子郵件地址。
<ArrayOfKeyValueOfstringanyType xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<KeyValueOfstringanyType>
<Key>Email</Key>
<Value xmlns:d3p1="http://www.w3.org/2001/XMLSchema" i:type="d3p1:string">[email protected]</Value>
</KeyValueOfstringanyType>
</ArrayOfKeyValueOfstringanyType>
到目前為止,我得到的最接近的是這個......它運行并說行受到影響但什么都不做。
update t
set XMLColumn.modify('replace value of (/ArrayOfKeyValueOfstringanyType/KeyValueOfstringanyType/Key/Value/string())[1] with "[email protected]"')
在查看了其他帖子和 Microsoft 的檔案后(https://docs.microsoft.com/en-us/sql/t-sql/xml/replace-value-of-xml-dml?view=sql-server-ver15#a- replace -values-in-an-xml-instance --Item D),看來我缺少一些關于命名空間的東西。如果我正確理解 XML,似乎有多個名稱空間要宣告。經過多次嘗試但沒有成功,我缺乏 XML 經驗讓我轉向這里。
任何幫助是極大的贊賞!
uj5u.com熱心網友回復:
請嘗試以下解決方案。
正如您正確猜到的,罪魁禍首是默認命名空間。
另外,我不得不調整 XPath 運算式。
SQL
-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, XMLColumn XML);
INSERT INTO @tbl (XMLColumn) VALUES
(N'<ArrayOfKeyValueOfstringanyType xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<KeyValueOfstringanyType>
<Key>Email</Key>
<Value xmlns:d3p1="http://www.w3.org/2001/XMLSchema"
i:type="d3p1:string">[email protected]</Value>
</KeyValueOfstringanyType>
</ArrayOfKeyValueOfstringanyType>');
-- DDL and sample data population, end
-- before
SELECT * FROM @tbl;
;WITH XMLNAMESPACES(DEFAULT 'http://schemas.microsoft.com/2003/10/Serialization/Arrays')
UPDATE @tbl
SET XMLColumn.modify('replace value of (/ArrayOfKeyValueOfstringanyType/KeyValueOfstringanyType/Value/text())[1] with "[email protected]"');
-- after
SELECT * FROM @tbl;
uj5u.com熱心網友回復:
您必須宣告默認命名空間
DECLARE @XML XML = N'<ArrayOfKeyValueOfstringanyType xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<KeyValueOfstringanyType>
<Key>Email</Key>
<Value xmlns:d3p1="http://www.w3.org/2001/XMLSchema" i:type="d3p1:string">[email protected]</Value>
</KeyValueOfstringanyType>
</ArrayOfKeyValueOfstringanyType> '
set @XML.modify('
declare default element namespace "http://schemas.microsoft.com/2003/10/Serialization/Arrays";
replace value of (/ArrayOfKeyValueOfstringanyType/KeyValueOfstringanyType/Value/text())[1] with "[email protected]"')
SELECT @XML
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/339044.html
標籤:sql sql-server xml
