Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-Sql xml query with namespace

Tags:

tsql

xml

This is a follow up question to

T-Sql xml query

If I add a namespace to xml data, nothing is returned again.

DECLARE @xVar XML
SET @xVar = 
  '<ReportData ObjectId="123" xmlns="http://ait.com/reportdata">
  <ReportId>AAAA-BBBB-CCCCC-DDDDD</ReportId>
  <DocId>100</DocId>
  <ReportName>Drag Scraper Troubleshooting</ReportName>
  <DocType>Name</DocType>
  <StatusId>1</StatusId>
  <AuthorId>1</AuthorId>
   </ReportData>'

SELECT [ReportId]= reportdata.item.value('.', 'varchar(40)') 
FROM   @xVar.nodes('/ReportData/ReportId[1]') AS reportdata(item) 

The above query returns nothing. Secondly, how would I select all elements in a single select and return a row with all elements as fields?

I want to return a record constructed as the following:

ReportId              | DocId | ReportName | 
AAAA-BBBB-CCCCC-DDDDD | 100   | AAAA-BBBB-CCCCC-DDDDD |
like image 916
klashagelqvist Avatar asked Jan 18 '12 12:01

klashagelqvist


People also ask

How to add namespace to XML in SQL?

To add namespaces to the XML constructed by the FOR XML query, first specify the namespace prefix to URI mappings by using the WITH NAMESPACES clause. Then, use the namespace prefixes in specifying the names in the query as shown in the following modified query.

How to add namespace in XML?

When using prefixes in XML, a namespace for the prefix must be defined. The namespace can be defined by an xmlns attribute in the start tag of an element. The namespace declaration has the following syntax. xmlns:prefix="URI".

What is Namespace in XML with examples?

An XML namespace is a collection of names that can be used as element or attribute names in an XML document. The namespace qualifies element names uniquely on the Web in order to avoid conflicts between elements with the same name.

What is XML schema namespace?

As defined by the W3C Namespaces in XML Recommendation , an XML namespace is a collection of XML elements and attributes identified by an Internationalized Resource Identifier (IRI); this collection is often referred to as an XML "vocabulary."


1 Answers

If you are trying to extract data and the namespace might differ between records, you can use a wildcard for the namespace prefix. Just put "*:" before each element name in the last line of the OP's original code, like this:

FROM   @xVar.nodes('/*:ReportData/*:ReportId[1]') AS reportdata(item) 

Note that you need to use the wildcard at every level, not just at the same level as you see a namespace declaration in the xml. This is because namespaces are inherited by each level from the level above it.

like image 198
Andrew Partridge Avatar answered Nov 05 '22 02:11

Andrew Partridge