簡體   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