仅在openxml中获取指定节点的子节点
Posted
技术标签:
【中文标题】仅在openxml中获取指定节点的子节点【英文标题】:Getting children node only of specified node in openxml 【发布时间】:2014-08-01 03:18:13 【问题描述】:我正在将 XML 文档导入 SQL 表。它是嵌套的 xml。我需要做3张桌子。我决定使用游标。我正在使用第一个光标逐行查找主节点。它可以完美地添加到第一个表中。将其添加到表后,我只想使用另一个游标访问 FROM OPENXML 语句中的某些子节点。到目前为止,我设法读取了每个子节点数据,而不仅仅是我感兴趣的一个。你能告诉我如何只进入我正在用我的第一个光标读取的那个父节点的子节点吗?
<root>
<mainnode>
<name>Main node 1</name>
<children>
<childrenname>Children name1</childrenname>
</children>
<children>
<childrenname>Children name2</childrenname>
</children>
</mainnode>
<mainnode>
<name>Main node 2</name>
<children>
<childrenname>Children name3</childrenname>
</children>
<children>
<childrenname>Children name4</childrenname>
</children>
</mainnode>
</root>
假设这是我的带有数据的 XML 结构。我通过批量功能添加了它。我现在做的是
DECLARE @name varchar(400),
DECLARE kursor CURSOR LOCAL FORWARD_ONLY FOR SELECT name from OPENXML(@DocID, 'root/mainnode', 2)
WITH name
open kursor
FETCH NEXT FROM kursor into @name
WHILE @@FETCH_STATUS = 0
BEGIN
--here i am adding record to first table, one by one with some insert
--and also here i need to reach children elements, but only of that certain mainnode
-- thats also the place to add second kursor
DECLARE childrenname varchar(400),
DECLARE kursorchildren CURSOR LOCAL FORWARD_ONLY FOR SELECT childrenname from OPENXML(@DocID, 'root/mainnode/children', 2)
WITH childrenname
OPEN kursorchildren
FETCH NEXT FROM kursorchildren into @childrenname
WHILE @@FETCH_STATUS = 0
BEGIN
--here i want to insert into table again, but only that childrens that are from actual row, not every form document.
FETCH NEXT FROM kursorchildren into @childrenname
END
CLOSE kursorchildren
DEALLOCATE kursorchildren
FETCH NEXT FROM kursor into @name
END
CLOSE kursorClaimsMain
DEALLOCATE kursorClaimsMain
【问题讨论】:
请在您的问题中添加一些数据和表结构,也可能是示例代码,如果您添加 sqlfiddle.com 演示会更好:) 我为你添加了部分代码 【参考方案1】:尝试像这样将其选择到普通表格中:
declare @xml xml = N'<root>
<mainnode>
<name>Main node 1</name>
<children>
<childrenname>Children name1</childrenname>
</children>
<children>
<childrenname>Children name2</childrenname>
</children>
</mainnode>
<mainnode>
<name>Main node 2</name>
<children>
<childrenname>Children name3</childrenname>
</children>
<children>
<childrenname>Children name4</childrenname>
</children>
</mainnode>
</root>'
select
t.value('.','nvarchar(max)') as children_name
,t.value('(../name)[1]','nvarchar(max)') as node_name
,t.value('for $a in .. return 1+count($a/../*[. << $a])', 'int') as code_id
from @xml.nodes('root/mainnode/children') t(t)
您将获得每个主要代码和子级列表的身份。因此,您可以提取到任何您想要的表格。
【讨论】:
以上是关于仅在openxml中获取指定节点的子节点的主要内容,如果未能解决你的问题,请参考以下文章