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 |
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.
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".
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.
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."
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With