Sql server 在SQL Server 2005中查询xml以获取结构而不是数据
我想查询有关XML的元数据,以帮助确定一些XML的结构。我有一个49MB的xml文件,我只需要知道所有属性和子标记的列表以及关于它们的一些基本信息。我可以从XML本身查询它吗?或者我必须费力地遍历它并找到其中可能存在的每个元素和属性吗?没有可用的架构定义 给定一些随机XML,如下所示:Sql server 在SQL Server 2005中查询xml以获取结构而不是数据,sql-server,xml,sql-server-2005,xsd,Sql Server,Xml,Sql Server 2005,Xsd,我想查询有关XML的元数据,以帮助确定一些XML的结构。我有一个49MB的xml文件,我只需要知道所有属性和子标记的列表以及关于它们的一些基本信息。我可以从XML本身查询它吗?或者我必须费力地遍历它并找到其中可能存在的每个元素和属性吗?没有可用的架构定义 给定一些随机XML,如下所示: DECLARE @x xml SET @x = '<People> <Person age="35"> <Name>Pete</Name> <
DECLARE @x xml
SET @x =
'<People>
<Person age="35">
<Name>Pete</Name>
<Phone>
<Mobile>555-555-1234</Mobile>
<Home>555-555-0001</Home>
</Phone>
</Person>
<Person age="40" height="70 inches">
<Name>Paul</Name>
<Phone>
<Mobile>555-555-4567</Mobile>
</Phone>
</Person>
<Person age="24">
<Name>Susan</Name>
<Phone>
<Home>555-555-2323</Home>
</Phone>
</Person>
</People>'
如下面的查询所示,提取结构是可行的,但正如John所说。。。为什么?如果需要强制约束,则使用xsd,并将其读入应用程序
declare @data xml
set @data = '
<People>
<Person age="35">
<Name>Pete</Name>
<Phone>
<Mobile>555-555-1234</Mobile>
<Home>555-555-0001</Home>
</Phone>
</Person>
<Person age="40" height="70 inches">
<Name>Paul</Name>
<Phone>
<Mobile>555-555-4567</Mobile>
</Phone>
</Person>
<Person age="24">
<Name>Susan</Name>
<Phone>
<Home>555-555-2323</Home>
</Phone>
</Person>
</People>'
;with c_Tree (Parent, Node)
as ( select p.n.value('local-name(..)[1]', 'varchar(max)'),
p.n.value('local-name(.)[1]', 'varchar(max)')
from @data.nodes('//*[local-name(.) > ""]') p(n)
),
c_Expand(lvl, RootName, NodeName)
as ( select 0,
Parent,
Node
from c_Tree
where Parent = ''
union all
select ce.lvl + 1,
ct.Parent,
ct.Node
from c_Tree ct
join c_Expand ce on
ce.NodeName = ct.Parent
)
select RootName+'>'+NodeName,
lvl
from c_Expand
order
by lvl asc;
这种类型的分析可能最好通过结构化程序代码来完成。仅仅因为xml可能在数据库中,并不意味着必须在数据库中进行xml分析。为什么要使用SQL Server进行此操作?这一点很好。我昨天在想这个。虽然能够进行这种元分析非常方便,但我认为真正的答案是启动一个XML库,自己进行分析。
declare @data xml
set @data = '
<People>
<Person age="35">
<Name>Pete</Name>
<Phone>
<Mobile>555-555-1234</Mobile>
<Home>555-555-0001</Home>
</Phone>
</Person>
<Person age="40" height="70 inches">
<Name>Paul</Name>
<Phone>
<Mobile>555-555-4567</Mobile>
</Phone>
</Person>
<Person age="24">
<Name>Susan</Name>
<Phone>
<Home>555-555-2323</Home>
</Phone>
</Person>
</People>'
;with c_Tree (Parent, Node)
as ( select p.n.value('local-name(..)[1]', 'varchar(max)'),
p.n.value('local-name(.)[1]', 'varchar(max)')
from @data.nodes('//*[local-name(.) > ""]') p(n)
),
c_Expand(lvl, RootName, NodeName)
as ( select 0,
Parent,
Node
from c_Tree
where Parent = ''
union all
select ce.lvl + 1,
ct.Parent,
ct.Node
from c_Tree ct
join c_Expand ce on
ce.NodeName = ct.Parent
)
select RootName+'>'+NodeName,
lvl
from c_Expand
order
by lvl asc;