-3

我有一个 XML 文件,我需要在其中选择值namevalue标记。

<parameter_set>
<parameter>
  <name>device_index</name>
  <type>1</type>
  <state>1</state>
  <value>1</value>
</parameter>
<parameter>
  <name>trx_index</name>
  <type>1</type>
  <state>1</state>
  <value>3</value>
</parameter>
</parameter_set>`enter code here`

我需要类似的选择名称和所有参数的值

4

3 回答 3

2
declare @XML xml 
set @XML = '
<parameter_set>
<parameter>
  <name>device_index</name>
  <type>1</type>
  <state>1</state>
  <value>1</value>
</parameter>
<parameter>
  <name>trx_index</name>
  <type>1</type>
  <state>1</state>
  <value>3</value>
</parameter>
</parameter_set>'

select T.N.value('(name/text())[1]', 'nvarchar(100)') as name,
       T.N.value('(value/text())[1]', 'nvarchar(100)') as value
from @XML.nodes('/parameter_set[1]/parameter') as T(N)

XQuery 语言参考 (SQL Server)

于 2013-08-29T07:52:26.027 回答
1

您可以OPENXML为此使用:

DECLARE @nDoc int
DECLARE @xml xml 

SET @xml = '<parameter_set>
<parameter>
  <name>device_index</name>
  <type>1</type>
  <state>1</state>
  <value>1</value>
</parameter>
<parameter>
  <name>trx_index</name>
  <type>1</type>
  <state>1</state>
  <value>3</value>
</parameter>
</parameter_set>'

EXEC sp_xml_preparedocument @nDoc OUTPUT, @xml

SELECT *
        FROM OPENXML(@nDoc, '/parameter_set/parameter', 1)
        WITH(
            name    nvarchar(MAX)   'name',
            value   nvarchar(MAX)   'value'
        )

EXEC sp_xml_removedocument @nDoc
于 2013-08-29T07:45:04.153 回答
1

试试这个——

DECLARE @XML XML
SELECT @XML = '
<parameter_set>
    <parameter>
      <name>device_index</name>
      <type>1</type>
      <state>1</state>
      <value>1</value>
    </parameter>
    <parameter>
      <name>trx_index</name>
      <type>1</type>
      <state>1</state>
      <value>3</value>
    </parameter>
</parameter_set>'

SELECT 
      name = t.c.value('name[1]', 'VARCHAR(50)')
    , [type]= t.c.value('type[1]', 'INT')
    , [state]= t.c.value('state[1]', 'INT')
    , value = t.c.value('value[1]', 'INT')
FROM @XML.nodes('parameter_set/parameter') t(c)

输出 -

name            type        state       value
--------------- ----------- ----------- -----------
device_index    1           1           1
trx_index       1           1           3
于 2013-08-29T07:53:28.473 回答