I have a database with tables that have schemaless XML columns which contain arbitrary non-XML data (plain-text). Here a sample script to gerenate and fill such a table:
CREATE TABLE TestTable (
ID INT NOT NULL IDENTITY (1, 1),
XmlColumn XML NOT NULL,
CONSTRAINT [PK_TestTable] PRIMARY KEY CLUSTERED (ID ASC) ON [PRIMARY]
) ON [PRIMARY]
GO
INSERT INTO TestTable (XmlColumn) VALUES ('<root><child /></root>');
INSERT INTO TestTable (XmlColumn) VALUES ('Foo, this is not XML');
INSERT INTO TestTable (XmlColumn) VALUES ('<root><parent><child /></parent></root>');
GO
How can I (preferred) enforce that only well-formed XML can be added?
Or else, how can I determine which entries are not well-formed and NULL
them out?
I have read several posts that suggest a CAST
/ CONVERT
in conjunction with a TRY CATCH
, (e.g. stackoverflow.com/questions/14753119), but I never get an exception, the CAST
/ CONVERT
always succeeds:
DECLARE @xml AS XML;
DECLARE @isValid AS BIT = 1;
BEGIN TRY
SET @xml = CONVERT(xml, 'Foo')
END TRY
BEGIN CATCH
SET @isValid = 0;
END CATCH;
SELECT @isValid; -- returns 1
Any ideas?
question from:
https://stackoverflow.com/questions/65617930/how-to-check-whether-a-string-is-well-formed-xml-in-sql-server 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…