从SQL解析XML文件

问题描述 投票:0回答:1

[嗨,我试图从SQL解析XML文件。但是路径似乎找不到数据。我不确定路径是否正确。以下是我拥有的示例xml文件:

   if OBJECT_ID('temp') is not null
drop table temp


CREATE TABLE temp (data xml);
insert into temp values
(' <Services>
    <Service Name="AlternativeCreditAttributes">
      <Categories>
        <Category Name="Default">
          <Attributes>
             <Attribute Name="ACA_TOF_Days_Since_LAST_PAYMENT" Value="15" />
          </Attributes>
        </Category>
      </Categories>
    </Service>
  </Services>
');
GO

下面是我的data.value代码:

SELECT data.value('(Services/Service [@Name="AlternativeCreditAttributes"]/Categories/Category[@Name="Default"]/Attributes/Attribute[@Name="ACA_TOF_Days_Since_LAST_PAYMENT"])[1]', 'varchar(100)')
FROM   temp;
GO
sql sql-server xml xml-parsing
1个回答
0
投票

正如您正确说的,您的XPath已完全关闭。这是@Value属性检索的起点。

SQL

-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, xml_data XML);
INSERT INTO @tbl (xml_data)
VALUES ('<Services>
    <Service Name="AlternativeCreditAttributes">
      <Categories>
        <Category Name="Default">
          <Attributes>
             <Attribute Name="ACA_TOF_Days_Since_LAST_PAYMENT" Value="15" />
          </Attributes>
        </Category>
      </Categories>
    </Service>
  </Services>');
-- DDL and sample data population, end

SELECT col.value('(@Value)[1]', 'VARCHAR(100)') AS [Value]
FROM @tbl AS tbl
    CROSS APPLY tbl.xml_data.nodes('/Services/Service[@Name="AlternativeCreditAttributes"]/Categories/Category[@Name="Default"]/Attributes/Attribute[@Name="ACA_TOF_Days_Since_LAST_PAYMENT"]') AS tab(col);

输出

+-------+
| Value |
+-------+
|    15 |
+-------+
© www.soinside.com 2019 - 2024. All rights reserved.