1

我有看起来像这样的示例 Xml:

<tst:Root xmlns:tst="http://tempuri.org/some.xsd" SchemaVersion="0.2.1234.12345" RevNumber="1">
  <tst:stuff someID="1">This is <tst:comment>1st.</tst:comment> what I <tst:comment>2nd</tst:comment>just want to show</tst:stuff>
</tst:Root>

我怎样才能返回“这就是我只想展示的”?

这是表格和我尝试过的。

CREATE TABLE [dbo].[XmlTable](
    [XmlId] [int] IDENTITY(1,1) NOT NULL,
    [XmlDoc] [xml] NOT NULL,
 CONSTRAINT [PK_XmlTable] PRIMARY KEY CLUSTERED 
(
    [XmlId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
SET IDENTITY_INSERT [dbo].[XmlTable] ON 

INSERT [dbo].[XmlTable] ([XmlId], [XmlDoc]) VALUES (1, N'<tst:Root xmlns:tst="http://tempuri.org/some.xsd" SchemaVersion="0.2.1234.12345" RevNumber="1"><tst:stuff someID="1">This is <tst:comment>1st.</tst:comment> what I <tst:comment>2nd</tst:comment>just want to show</tst:stuff></tst:Root>')
SET IDENTITY_INSERT [dbo].[XmlTable] OFF

以及我尝试过的:

这个只按预期返回“This is”。

--WITH XMLNAMESPACES (Default 'http://tempuri.org/some.xsd')
--SELECT     

--  a.value('text()[1]', 'nvarchar(100)') as SampleXml
--  From
--  XmlTable As x
--  Cross Apply XmlDoc.nodes('Root/stuff') a(a)

这个正在返回一切:“这是第一个。我第二个想要展示的东西”

WITH XMLNAMESPACES (Default 'http://tempuri.org/some.xsd')
SELECT     

    a.value('.', 'nvarchar(100)') as SampleXml
    From
    XmlTable As x
    Cross Apply XmlDoc.nodes('Root/stuff') a(a)

如何排除评论节点,但仍能得到正确的结果?

编辑:

我想这样退货:

在此处输入图像描述

有没有比以下更简单的方法:

WITH XMLNAMESPACES (Default 'http://tempuri.org/some.xsd')
SELECT     

a.value('text()[1]', 'nvarchar(100)') + a.value('text()[2]', 'nvarchar(100)') + a.value('text()[3]', 'nvarchar(100)')  as SampleXml

From
XmlTable As x
Cross Apply XmlDoc.nodes('Root/stuff') a(a)
4

1 回答 1

2

尝试这个:

 declare @xml xml;

 set @xml = convert(xml, 'your XML');

 with xmlnamespaces (Default 'http://tempuri.org/some.xsd')
 select @xml.query('//stuff/text()')

假设您有一个带有 XML 列的表,它看起来像这样:

 -- Set up the XML table to demonstrate
 declare @table table
 (
      ID int,
      xmlDoc  xml
 )

 -- insert your example XML
 insert into @table 
 Values (1, '<tst:Root xmlns:tst="http://tempuri.org/some.xsd" SchemaVersion="0.2.1234.12345" RevNumber="1"><tst:stuff someID="1">This is <tst:comment>1st.</tst:comment> what I <tst:comment>2nd</tst:comment>just want to show</tst:stuff></tst:Root>');

 -- Do the query
 with xmlnamespaces (Default 'http://tempuri.org/some.xsd')
 select ID, xmlDoc.query('//Root/stuff/text()') as SampleXml
 from @table

这就是我的结果:

在此处输入图像描述

于 2013-11-03T01:43:31.033 回答