我已经看过一些XML解析示例,并尝试了几个,但我坚持如何显示所有行
我的H:\ Sample.xml文件如下所示:
<?xml version="1.0" encoding="utf-8"?>
<Level1>
<Level2>
<Level3>
<Data>Line1</Data>
<Data>Line2</Data>
<Data>Line3</Data>
<Data>Line4</Data>
</Level3>
</Level2>
</Level1>
我的级别没有附加值,我只想生成4条数据行的列。
我尝试了三种方法:
第一种方法:使用OpenRowSet和.nodes
DECLARE @Data XML
SET @Data = ( SELECT CONVERT(XML, BulkColumn) AS BulkColumn
FROM OPENROWSET(BULK 'H:\Sample.xml', SINGLE_BLOB) as X )
SELECT
a.b.value('Data[1]','nvarchar(255)') as Detail
FROM @Data.nodes('Level1/Level2/Level3')a(b)
第二种方法:使用交叉应用
WITH xmlFile (Contents) AS (
SELECT CONVERT(XML, BulkColumn) AS BulkColumn
FROM OPENROWSET(BULK 'H:\Sample.xml', SINGLE_BLOB) as XmlData
)
SELECT
c.value('(Data)[1]', 'varchar(255)') AS Detail
FROM XmlFile CROSS APPLY Contents.nodes ('(//Level1/Level2/Level3)') AS t(c);
第三种方法:使用sp_xml_preparedocument
DECLARE @hDoc AS INT
DECLARE @SQL NVARCHAR (MAX)
EXEC sp_xml_preparedocument @hDoc OUTPUT, @Data
SELECT Detail
FROM OPENXML(@hDoc, 'Level1/Level2/Level3')
WITH (Detail [varchar](255) '@Data')
EXEC sp_xml_removedocument @hDoc
GO
前两个例子显示&#34; Line1&#34;最后一个显示NULL(每个只有一行)
答案 0 :(得分:1)
你的第一次尝试几乎就在那里,只需要更深层次了:
DECLARE @Data XML
SET @Data = ( SELECT CONVERT(XML, BulkColumn) AS BulkColumn
FROM OPENROWSET(BULK 'H:\Sample.xml', SINGLE_BLOB) as X )
SELECT
a.b.value('.','nvarchar(255)') as Detail
FROM @Data.nodes('Level1/Level2/Level3/Data')a(b)
答案 1 :(得分:0)
declare @data xml;
set @data = '<?xml version="1.0" encoding="utf-8"?>
<Level1>
<Level2>
<Level3>
<Data>Line1</Data>
<Data>Line2</Data>
<Data>Line3</Data>
<Data>Line4</Data>
</Level3>
</Level2>
</Level1>';
select x.i.value('.', 'varchar(100)') as Detail
from @data.nodes('//Level1/Level2/Level3/Data') as x(i);