I have an XML file where the nodes that I need the data from are all named the same. I understand how to access the first (or second record) so the following query only gives me the second author (the <a1>
tag). How do I get all the authors as a single column ?
DECLARE @MyXML XML
SET @MyXML = '<refworks>
<reference>
<rt>Journal Article</rt>
<sr>Print(0)</sr>
<id>869</id>
<a1>Aabye,Martine G.</a1>
<a1>Hermansen,Thomas Stig</a1>
<a1>Ruhwald,Morten</a1>
<a1>PrayGod,George</a1>
<a1>Faurholt-Jepsen,Daniel</a1>
<a1>Jeremiah,Kidola</a1>
<a1>Faurholt-Jepsen,Maria</a1>
<a1>Range,Nyagosya</a1>
</reference>
</refworks>'
SELECT
author.value('(a1)[2]', 'varchar(MAX)') AS 'Author'
FROM @MyXML.nodes('/refworks/reference') AS ref(author)
You should use the query() Method if you want to get a part of your XML. If you want the value from a specific node you should use value() Method. Update: If you want to shred your XML to multiple rows you use nodes() Method.
SQL Server lets you retrieve data as XML by supporting the FOR XML clause, which can be included as part of your query. You can use the FOR XML clause in the main (outer) query as well as in subqueries. The clause supports numerous options that let you define the format of the XML data.
You can optionally retrieve formal results of a SQL query as XML by specifying the FOR XML clause in the query. The FOR XML clause can be used in top-level queries and in subqueries. The top-level FOR XML clause can be used only in the SELECT statement.
Read the XML file using OPENROWSET, and save the data in the table. In the below code, we create a table for our raw XML data. Then read the XML file and save the same data into the "PointsXML" table. CREATE TABLE PointsXML -- Create table for raw XML file.
Try this :-
SELECT
author.value('./text()[1]', 'varchar(MAX)') AS 'Author'
FROM @MyXML.nodes('//refworks/reference/child::node()') AS ref(author)
where author.value('local-name(.)[1]', 'varchar(100)') ='a1'
child::node() represents an axis specifier which is child
and ::
is the axis separator.
For understanding child axis which is used to drill down in the node can be found in this MSDN document.
or manipulating xml data in sql server
Updated :-
A much simplier way You were on the right track .Specify the child node in the from clause for filtering the data
SELECT
author.value('(.)[1]', 'varchar(MAX)') AS 'Author'
FROM @MyXML.nodes('/refworks/reference/a1') AS ref(author)
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