繁体   English   中英

从 SQL 解析 XML 文件

[英]Parse XML file from SQL

嗨,我试图从 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

正如您所说的那样,您的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);

Output

+-------+
| Value |
+-------+
|    15 |
+-------+

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM