Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

t-sql: convert varchar to xml

I have some valid and invalid xml values stored in a varchar column.

I'd like to cast the valid xml values to the actual xml data type and invalid to nulls.

What's a good way to do this ?

Something like:

SELECT 
    CASE WHEN dbo.isValidXML(xml_data) THEN CAST(xml_data as XML)
    ELSE null 
END
like image 968
David Avatar asked Jul 30 '13 16:07

David


People also ask

Can you convert SQL to XML?

With SQL Server Management Studio, you can save your SQL database as CSV and then you can convert the database files to XML, PDF or other formats as you like.

Can SQL store XML?

Keep in mind that SQL Server stores XML data as large binary objects (BLOBS). When there is no index, the database engine shreds the XML at runtime when evaluating the query.

How can a XML file be created from a database?

Here we are going to create an XML file from Database. Make an SQL connection to the Database and execute the sql and store the data in a Datset. Call Dataset's WriteXml() method and pass the file name as argument. You have to pass necessary database connection information to connection string.

What is Sp_xml_preparedocument?

sp_xml_preparedocument returns a handle that can be used to access the newly created internal representation of the XML document. This handle is valid for the duration of the session or until the handle is invalidated by executing sp_xml_removedocument.


2 Answers

In response solely to this:

Yes, but the beef of my question is how do I check is XML is valid in the first place?

Is your XML invalid in the sense that you'll get a break like the second line below this:

SELECT CAST('<xml>Yep this is xml</xml>' AS XML)
SELECT CAST('<xml>Nope, not xml</x' AS XML)

One solution I see is a row-by-row approach, where you try and CAST a row as XML, and if it casts as XML successfully insert the valid row into a table with valid XML values, if it won't cast correctly, the value isn't inserted. See this thread for examples.

like image 137
Question3CPO Avatar answered Sep 21 '22 20:09

Question3CPO


Try to use sp_xml_preparedocument -

SET NOCOUNT ON;

DECLARE @XML NVARCHAR(MAX)
SELECT @XML = '<t>test</'

DECLARE @hDoc INT

BEGIN TRY

     EXEC sys.sp_xml_preparedocument @hDoc OUTPUT, @XML 
     SELECT '"' + @XML + '" is valid'
     EXEC sys.sp_xml_removedocument @hDoc

END TRY
BEGIN CATCH
     SELECT '"' + @XML + '" is invalid'     
END CATCH

SELECT @XML = '<t>test</t>'

BEGIN TRY

     EXEC sys.sp_xml_preparedocument @hDoc OUTPUT, @XML 
     SELECT '"' + @XML + '" is valid'
     EXEC sys.sp_xml_removedocument @hDoc

END TRY
BEGIN CATCH
     SELECT '"' + @XML + '" is invalid'     
END CATCH

Output -

-------------------------
"<t>test</" is invalid

-------------------------
"<t>test</t>" is valid
like image 23
Devart Avatar answered Sep 23 '22 20:09

Devart