简体   繁体   中英

Extract value from a sql column that contains XML

I'm trying to get the value from a column in a SQL Server table that contains XML but the type of the column is not XML it is TEXT .

I tried this:

SELECT 
    [Id],
    [Request]
FROM 
    [Tracker] 
WHERE 
    [Request].value('/Credit[1]/Loan[1]/LoanApp[1]/Applicant[1]/Personal[1]/Individals[1]/Individual[1]/GivenName[1]/FirstName[1]', 'nvarchar(50)') = 'Tom'

but I get this error :

Cannot find either column "Request" or the user-defined function or aggregate "Request.value", or the name is ambiguous.

I tried to cast the column like this:

select  
    CAST(CAST(Request AS NTEXT) AS XML).value('(/Credit[1]/Loan[1]/LoanApp[1]/Applicant[1]/Personal[1]/Individuals[1]/Individual[1]/GivenName[1]/FirstName[1]', 'nvarchar(50)') 
from Tracker

but with this I get this error:

XML parsing: line 1, character 15, A string literal was expected

I tried the solution in this link: Unable to cast TEXT to XML in SQL Server

  XML parsing: line 1, character 15, A string literal was expected

This is what I have tried:

 SELECT 
  CAST(
  REPLACE(CAST(Request AS VARCHAR(MAX)), 'encoding="utf-16"',   'encoding="utf-8"')
AS     XML).value('(Credit/Loan/App/Applicant/Personal/Individuals/Individual/GivenName/FirstName/text())[1]', 'NVARCHAR(max)') as UserGuid
 FROM Tracker

Your casting is correct

select  CAST(CAST(Request AS NTEXT)AS  
   XML).value('(/Credit[1]/Loan[1]/LoanApp[1]/Applicant[1]/Personal[1]/Individuals[1]/Individual[1]/GivenName[1]/FirstName[1]', 'nvarchar(50)') 

from Tracker]

But one of the possible reasons you are getting the error is you haven't specified the attributes in a single or double quote.

As an example you have <credit id=12> in your Request text field and you need to change it to <credit id='12'> or <credit id="12"> before casting it to XML.

将对象转换为String ,然后使用XmlTextReaderReadXml

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM