从SQL Server中的XML文件中删除节点

时间:2015-10-23 15:24:03

标签: sql sql-server xml tsql xquery

我有一个从Excel导出的XML文件,该文件存储在SQL Server的表中的XML列中。 Excel文件有很多工作表,我只想存储一些工作表。有没有办法删除那些没有我要保留的名称的节点,类似于NOT IN

XML文件有这个标题:

<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:o="urn:schemas-microsoft-com:office:office"
 xmlns:x="urn:schemas-microsoft-com:office:excel"
 xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:html="http://www.w3.org/TR/REC-html40">

这是XML的基本结构:

<Workbook>
  <DocumentProperties>
  </DocumentProperties>
  <ExcelWorkbook>
  </ExcelWorkbook>
  <Styles>
    <Style>
    </Style>
  </Styles>
  <Worksheet ss:Name="Worksheet1">
    <Table>
      <Column.../>
      <Column.../>
      <Column.../>
      <Row>
        <Cell.../>
        <Cell><Data>...</Data></Cell>
        <Cell><Data>...</Data></Cell>
        <Cell><Data>...</Data></Cell>
        <Cell><Data>...</Data></Cell>
        <Cell.../>
      </Row>
      ...
    </Table>
  </Worksheet>

并且节点重复几次。让我们说我只想保留&#34;工作表3&#34;,&#34;工作表4&#34;和&#34;工作表8&#34;。我怎么能这样做?我想我想在这种情况下使用updatemodify(),类似于this question。唯一的区别是我想保留某些值,并删除其余值。

1 个答案:

答案 0 :(得分:1)

试试这样:

DECLARE @xml XML=
'<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:o="urn:schemas-microsoft-com:office:office"
 xmlns:x="urn:schemas-microsoft-com:office:excel"
 xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:html="http://www.w3.org/TR/REC-html40">
  <DocumentProperties>
  </DocumentProperties>
  <ExcelWorkbook>
  </ExcelWorkbook>
  <Styles>
    <Style>
    </Style>
  </Styles>
  <Worksheet ss:Name="Worksheet1">
    <Table>
      <Column/>
      <Column/>
      <Column/>
      <Row>
        <Cell.../>
        <Cell><Data>...</Data></Cell>
        <Cell><Data>...</Data></Cell>
        <Cell><Data>...</Data></Cell>
        <Cell><Data>...</Data></Cell>
      </Row>
    </Table>
  </Worksheet>
  <Worksheet ss:Name="Worksheet2">
    <Table>
      <Column/>
      <Column/>
      <Column/>
      <Row>
        <Cell.../>
        <Cell><Data>...</Data></Cell>
        <Cell><Data>...</Data></Cell>
        <Cell><Data>...</Data></Cell>
        <Cell><Data>...</Data></Cell>
      </Row>
    </Table>
  </Worksheet>
  <Worksheet ss:Name="Worksheet3">
    <Table>
      <Column/>
      <Column/>
      <Column/>
      <Row>
        <Cell.../>
        <Cell><Data>...</Data></Cell>
        <Cell><Data>...</Data></Cell>
        <Cell><Data>...</Data></Cell>
        <Cell><Data>...</Data></Cell>
      </Row>
    </Table>
  </Worksheet>
</Workbook>';

SET @xml.modify('declare namespace dflt="urn:schemas-microsoft-com:office:spreadsheet";
                 declare namespace ss="urn:schemas-microsoft-com:office:spreadsheet"; 
                 delete /dflt:Workbook/dflt:Worksheet[@ss:Name="Worksheet2"]');

SELECT @xml;

您可以将多个过滤器表达式与&#34;或&#34; ...

组合在一起