0

任何人都可以帮我处理下面的xml。我需要提取所有 xml 值,如下所示。

AwarYear   Comments                         FieldCode   FieldNumber  Key    Value
AY2013-14  AAI: Adjusted Available Income   AAI            306       Blank  None Calculated

这是示例 XML。

<SchemaType xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/process">
  <AwardYear>AY2013_14</AwardYear>
  <Fields>
    <FieldSchema>
      <Comments>AAI: Adjusted Available Income</Comments>
      <DbLocation>IsirData</DbLocation>
      <FieldCode>AAI</FieldCode>
      <FieldNumber>306</FieldNumber>
      <ReportDisplay>Data</ReportDisplay>
      <ValidContent>
       <ValidValueContent xmlns:d5p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
          <d5p1:KeyValueOfstringstring>
            <d5p1:Key>Blank</d5p1:Key>
            <d5p1:Value>None calculated</d5p1:Value>
          </d5p1:KeyValueOfstringstring>
        </ValidValueContent>
      </ValidContent>
    </FieldSchema>
      </Fields>
</SchemaType>

请做需要的充分。提前致谢。

4

1 回答 1

4

假设您的 XML 在这样的XML列内的表中:

DECLARE @XmlTable TABLE (ID INT NOT NULL, XMLDATA XML)

INSERT INTO @XmlTable VALUES(1, '<SchemaType xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/process">
  <AwardYear>AY2013_14</AwardYear>
  <Fields>
    <FieldSchema>
      <Comments>AAI: Adjusted Available Income</Comments>
      <DbLocation>IsirData</DbLocation>
      <FieldCode>AAI</FieldCode>
      <FieldNumber>306</FieldNumber>
      <ReportDisplay>Data</ReportDisplay>
      <ValidContent>
       <ValidValueContent xmlns:d5p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
          <d5p1:KeyValueOfstringstring>
            <d5p1:Key>Blank</d5p1:Key>
            <d5p1:Value>None calculated</d5p1:Value>
          </d5p1:KeyValueOfstringstring>
        </ValidValueContent>
      </ValidContent>
    </FieldSchema>
      </Fields>
</SchemaType>')

那么你可以使用这个 T-SQL 语句来获取值:

;WITH XMLNAMESPACES(DEFAULT 'http://schemas.datacontract.org/process', 
                    'http://schemas.microsoft.com/2003/10/Serialization/Arrays' AS ns1)
SELECT
    AwardYear = XmlData.value('(SchemaType/AwardYear)[1]', 'varchar(25)'),
    Comments = XmlData.value('(SchemaType/Fields/FieldSchema/Comments)[1]', 'varchar(50)'),
    FieldCode = XmlData.value('(SchemaType/Fields/FieldSchema/FieldCode)[1]', 'varchar(10)'),
    FieldNumber = XmlData.value('(SchemaType/Fields/FieldSchema/FieldNumber)[1]', 'int'),
    [Key] = XmlData.value('(SchemaType/Fields/FieldSchema/ValidContent/ValidValueContent/ns1:KeyValueOfstringstring/ns1:Key)[1]', 'varchar(10)'),
    [Value] = XmlData.value('(SchemaType/Fields/FieldSchema/ValidContent/ValidValueContent/ns1:KeyValueOfstringstring/ns1:Value)[1]', 'varchar(10)')
FROM
    @XmlTable

我将顶级 XML 命名空间定义为“默认”命名空间(不需要到处引用),结构深处的第二个命名空间使用单独的 XML 命名空间前缀显式定义。

于 2014-01-10T06:05:50.310 回答