如何获取xml节点的数量

时间:2019-02-20 03:27:05

标签: sql sql-server xml sql-server-2008

我有以下xml节点

<PPAProposal xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Answers>
<AnswersList>
<Entry key="ac5_a_InsuredDetailsUpload" type="System.Collections.ArrayList">
        <value>
          <anyType xsi:type="xsd:string">C___documents__PPA_813FN0011684_190219_1003.pdf</anyType>
          <anyType xsi:type="xsd:string">New Doc 2019-02-18 13.37.43 (1).pdf</anyType>
        </value>
</Entry>
</Answers>
</AnswersList>
</PPAProposal>

我需要获取“ AnyType”节点的数量。 我写了类似下面的查询。

SELECT 
(CASE WHEN  Data.value('(/*/Answers/AnswersList/Entry[@key="ac5_a_InsuredDetailsUpload"]/value)[1]', 'nvarchar(max)')!=''
            THEN 

             (SELECT Count((ISNULL(Col.value('(value)[1]', 'nvarchar(max)'), '0'))) AS upload
          FROM Data.nodes('(/*/Answers/AnswersList/Entry[@key="ac5_a_InsuredDetailsUpload"])') AS Tbl(Col))

      ELSE  0
      END
    )
FROM TEMPTABLE

我可以返回计数1而不是计数2,因为“值”节点中有2个节点。

2 个答案:

答案 0 :(得分:1)

您可以直接在XPath中计算anyType个元素:

SELECT 
  t.Data.value(
    'count(/*/Answers/AnswersList/Entry[@key="ac5_a_InsuredDetailsUpload"]/value/anyType)', 
    'int'
  ) as anytype_count
FROM TEMPTABLE t;

dbfiddle demo

答案 1 :(得分:0)

declare @XMLDATA xml;
set @XMLDATA = '
<PPAProposal xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<AnswersList>
<Answers>
<Entry key="ac5_a_InsuredDetailsUpload" type="System.Collections.ArrayList">
    <value>
      <anyTypexsi:type="xsd:string">C___documents__PPA_813FN0011684_190219_1003.pdf</anyType>
      <anyType xsi:type="xsd:string">New Doc 2019-02-18 13.37.43 (1).pdf</anyType>
    </value></Entry></Answers></AnswersList></PPAProposal>'

DECLARE @XMLDocPointer INT; 
EXEC sp_xml_preparedocument @XMLDocPointer OUTPUT,@XMLDATA; 

    SELECT  value INTO #TEMPDATA

    FROM    OPENXML( @XMLDocPointer, '/PPAProposal/AnswersList/Answers/Entry/value/anyType', 2 )
            WITH ( value NVARCHAR(1000), anyType NVARCHAR(1000) )


EXEC sp_xml_removedocument @XMLDocPointer;

select count(*)total from #TEMPDATA
drop table #TEMPDATA