I've imported several XML files whilst gathering data into a SQL Server table.
I need to query this XML data column to transform the single XML column into a more structured table.
Can someone please help with the syntax here, the XML structure has a pattern hence once understood in SQL XML.query format it should be easy to repeat for all elements I want.
Select TOP 1
[XMLFILE].value('(/Objs/Obj[0]/TN)[0]','VARCHAR(MAX)') as TEST,
[XMLFILE].query('/Objs/Obj') as HEADERTEST,
[XMLFILE].query('/Ref[@id="0"]') as Property1
FROM
SQL_Table
The above just returns an empty string for every pattern I try.
I need to extract the name and value of each obj [] element.
XML structure example ie objs header followed by obj nodes 0 through to 'x' nodes.
<?xml version="1.0"?>
<Objs xmlns="xxxx" Version="1.1.0.1">
<Obj RefId="0">
<TN RefId="0">
<T>xxxx/T>
<T>xxxxx</T>
<T>xxxx</T>
</TN>
<MS>
<S N="Name">xxxx</S>
<S N="Value">xxxx</S>
</MS>
</Obj>
<Obj RefId="1">
<TNRef RefId="0"/>
<MS>
<S N="Name">xxxxxx</S>
<S N="Value"/>
</MS>
</Obj>
<Obj RefId="2">
<TNRef RefId="0"/>
<MS>
<S N="Name">xxxxx</S>
<S N="Value"/>
</MS>
</Obj>
<Obj RefId="3">
<TNRef RefId="0"/>
<MS>
<S N="Name">xxxx</S>
<S N="Value"/>
</MS>
</Obj>
......
......
</Objs>
Couple of problems:
Try this:
-- replace the 'xxx' with whatever is really defined in your <Objs xmlns=....>
;WITH XMLNAMESPACES(DEFAULT 'xxxx')
SELECT
RefId = xc.value('@RefId', 'int'),
Name = xc.value('(MS/S[@N="Name"])[1]', 'varchar(20)'),
Value = xc.value('(MS/S[@N="Value"])[1]', 'varchar(20)')
FROM
SQL_Table
CROSS APPLY
XmlFile.nodes('/Objs/Obj') AS XT(XC)
The CROSS APPLY
generates an on-the-fly virtual table of XML fragments for each XML node that matches the XPath expression - here, for each <Obj>
node under <Objs>
.
The XQuery method .value()
then "reaches" into that XML fragment (for each of the fragements in that virtual table) and pulls out the necessary desired info - here the RefId
attribute on the <Obj>
node, as well as the textual value of the <MS>/<SN="Name">
and <MS>/<SN="Value">
subnodes.
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.