在SQL Server中解析以下XML

时间:2018-09-11 08:08:36

标签: sql sql-server xml

XML看起来像这样:

<saw:deliveryContent format="comma" disposition="attachment" xmlns:saw="uri">
    <saw:headline>
        <saw:caption>
            <saw:text>Beer PMIX Data</saw:text>
        </saw:caption>
    </saw:headline>
    <saw:attachmentMessage>
        <saw:caption>
            <saw:text>Beer PMIX data used in the PMIX Data - ROQ Stars file.</saw:text>
        </saw:caption>
    </saw:attachmentMessage>
    <saw:reportRef path="Beer PMIX (Scheduled)"/>
</saw:deliveryContent>

我的结果表应包含

text ->Beer PMIX data used in the PMIX Data - ROQ Stars file.
reportRef path ->"Beer PMIX (Scheduled)

赞:text|reportRef path

是否可以直接从查询或存储过程中获取此值?

1 个答案:

答案 0 :(得分:0)

您的xml无效,因为没有前缀声明-saw

稍微修改的xml可以这样解析:

DECLARE @xml xml = '<saw:deliveryContent format="comma" disposition="attachment" xmlns:saw="uri">
    <saw:headline>
        <saw:caption>
            <saw:text>Beer PMIX Data</saw:text>
        </saw:caption>
    </saw:headline>
    <saw:attachmentMessage>
        <saw:caption>
            <saw:text>Beer PMIX data used in the PMIX Data - ROQ Stars file.</saw:text>
        </saw:caption>
    </saw:attachmentMessage>
    <saw:reportRef path="/shared/BJs Analytics/Departments/Planning/Jon/Agent Reports/Beer PMIX (Scheduled)"/>
</saw:deliveryContent>';

WITH XMLNAMESPACES ('uri' as saw)
SELECT
  @xml.value('(saw:deliveryContent/saw:headline/saw:caption/saw:text)[1]','nvarchar(max)'),
  @xml.value('(saw:deliveryContent/saw:attachmentMessage/saw:caption/saw:text)[1]','nvarchar(max)'),
  @xml.value('(saw:deliveryContent/saw:reportRef/@path)[1]','nvarchar(max)')