我有一个非常大的XML文档,正在将其加载到SQL中,然后尝试解析以添加到现有表的末尾。
到目前为止,我的代码是: '
INSERT INTO XMLAttempt1(XMLData, LoadedDateTime)
SELECT CONVERT(XML, Bulkcolumn) AS Bulkcolumn, getdate()
from openrowset(bulk 'filepath.xml', Single_clob) as x;
select * from XMLAttempt1
DECLARE @XML as XML, @hdoc int, @doc nvarchar(MAX);
SELECT @xml = XMLDATA FROM XMLAttempt1;
EXEC sp_xml_preparedocument @hdoc OUTPUT, @XML;
Select *
FROM OPENXML (@hdoc, 'CxXMLResults/Query/Result', 1)
WITH (ID int '../@id',
@NodeId INT @NodeId',
ProjectID int '../../@ProjectId',
ScanId int '../../@ScanId');
XML的格式为:
<Result NodeId="635920047" lots of other info>
<Path ResultId="63592" PathId="47" SimilarityId="-1924977021">
<PathNode>
<FileName></FileName>
<Line>292</Line>
<Column>82</Column>
<NodeId>1</NodeId>
<Name>SelectedValue</Name>
<Type></Type>
<Length>13</Length>
<Snippet>
<Line>
<Number>292</Number>
<Code> stuff;</Code>
</Line>
</Snippet>
</PathNode>
[next x numbers of PathNode]
</Path>
</Result>
<Result NodeId="635920048"
[etc until the next QueryId]
我看过这篇文章(Count the number of sub tags from XML in SQL),但我无法使它正常工作,并且我认为那是因为我尝试使用它的位置-我的语法不正确。
DECLARE @XML as XML, @hdoc int, @doc nvarchar(MAX);
SELECT @xml = XMLDATA FROM XMLAttempt1;
EXEC sp_xml_preparedocument @hdoc OUTPUT, @XML;
Select *
FROM OPENXML (@hdoc, 'CxXMLResults/Query/Result', 1)
WITH (ID int '../@id',
@XML.query('count(@NodeId') INT '@NodeId',
ProjectID int '../../@ProjectId',
ScanId int '../../@ScanId');
但是它说@XML的语法不正确
当前结果:
ID NodeID ProjectID ScanId
427 635920047 20336 63592
427 635920048 20336 63592
427 635920049 20336 63592
427 635920050 20336 63592
427 635920051 20336 63592
427 635920052 20336 63592
我想结束的是:
ID Count ofNodes ProjectID ScanId
427 6 20336 63592
任何帮助将不胜感激。
答案 0 :(得分:1)
您显示的XML不够,因此需要一些猜测...
但是首先:FROM OPENXML
已过时,不应再使用(存在罕见的例外)。宁可使用XML's native methods。
如前所述,这是疯狂的猜测
SELECT @XML.value('(/CxXMLResults/Query/@id)[1]','nvarchar(max)') AS id
,@XML.value('count(/CxXMLResults/Query/Result/@NodeId)','int') AS CountOfNodes
,@XML.value('(/CxXMLResults/@ProjectId)[1]','nvarchar(max)') AS ProjectId
,@XML.value('(/CxXMLResults/@ScanId)[1]','nvarchar(max)') AS ScanId
一些提示:
../../
的处理速度很慢,请尽量避免。xmlns="something"
)<CxXMLResults>
和<Query>
,并且id,ProjectId和ScanId的值存在于您未显示的部分中。