XPath SQL Server中的可选元素

huangapple go评论60阅读模式
英文:

Optional elements on XPath SQL Server

问题

我必须将XML文件导入到SQL Server数据库中。我正在使用OPENXML,但由于文件具有两种不同的布局(因为它在几年前进行了更新),我不知道如何在同一个函数中导入这两种布局。

我的当前代码如下:

FROM OPENXML(@idoc, N'ROOT/event1 /event2 /event3 /event4 /event5 /event6')

该代码对于较新的布局有效。

我的问题是,XML中的event3和event4元素仅出现在2022年10月之后生成的文件中。

是否有一种方法可以指出这两个元素是可选的?如果event3和event4不存在,函数是否可以“跳过”从event2到event5?

谢谢您的关注。

英文:

I have to import xml files to to a SQL Server Database. I am using OPENXML, but since the files have two different layouts (because it was updated a couple years ago) I don't know any way to import both layouts on the same function.

My current code is like this:

FROM OPENXML(@idoc, N'ROOT/event1 /event2 /event3 /event4 /event5 /event6')

The code is working for the newer layout.

My problem is that the event3 and event4 elements on the XML only appear in files that were generated after october 2022.

Is there a way to point that those two elements are optional? Any way the funcion can "jump" from event2 to event5 if event3 and event4 does not exist?

Thank you for your attention

答案1

得分: 1

你应该能够像这样做:

declare @x xml = '<ROOT><event1><event2><event3><event4><event5><event6>test</event6></event5></event4></event3></event2></event1></ROOT>'
declare @h int
exec sys.sp_xml_preparedocument @h output, @x
select *
FROM OPENXML(@h, N'ROOT/event1/event2//event5/event6')

exec sys.sp_xml_removedocument @h

OPENXML 有点老式了,你可能想要考虑一些更新的方法,比如 nodes 函数。

英文:

You should be able to do something like this:

declare @x xml = '<ROOT><event1><event2><event3><event4><event5><event6>test</event6></event5></event4></event3></event2></event1></ROOT>'
declare @h int
exec sys.sp_xml_preparedocument @h output, @x
select *
FROM OPENXML(@h, N'ROOT/event1/event2//event5/event6')

exec sys.sp_xml_removedocument @h

OPENXML is a bit old-school though, you might wanna look into something newer like the nodes function.

huangapple
  • 本文由 发表于 2023年7月18日 02:09:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76707077.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定