3

我正忙着将网站从 xml 文件库转换为 SQL Server 2012 express 数据库,现在我已经设法从 xml 中获取大部分标签以轻松导入 SQL Server

我现在的问题在于这些 xml 的特定部分

这是我遇到问题的部分

<?xml version="1.0" encoding="utf-16"?>
<License xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

<Reference>00b2d4cf-699c-4427-bcf0-a0ca456654c2</Reference>
 <MacAddresses>
  <string>00:0D:87:FE:9A:21</string>
  <string>00:20:ED:14:47:64</string>
  <string>00:13:D3:11:7C:D2</string>
  <string>00:13:D3:11:7C:D8</string>
  <string>00:19:D1:04:12:98</string>
  <string>00:19:66:C0:7F:AF</string>
 </MacAddresses>
</License>

我对每个许可证和分配给该许可证的 MAC 地址都有一个参考。
现在我希望它将它导入到 sql 中,如下所示:

Reference                               MACAddress
---------                               ----------
00b2d4cf-699c-4427-bcf0-a0ca456654c2    00:0D:87:FE:9A:21
00b2d4cf-699c-4427-bcf0-a0ca456654c2    00:20:ED:14:47:64
00b2d4cf-699c-4427-bcf0-a0ca456654c2    00:13:D3:11:7C:D2
00b2d4cf-699c-4427-bcf0-a0ca456654c2    00:13:D3:11:7C:D8
00b2d4cf-699c-4427-bcf0-a0ca456654c2    00:19:D1:04:12:98
00b2d4cf-699c-4427-bcf0-a0ca456654c2    00:19:D1:04:12:98
00b2d4cf-699c-4427-bcf0-a0ca456654c2    00:19:66:C0:7F:AF

我会手动完成,但我有 700 多个许可证可以导入,手动完成需要很长时间。

帮助将不胜感激

4

1 回答 1

1

如果您使用的是 SQL Server 2005 或更新版本,则可以使用本机 XQuery 支持从该 XML 中提取您想要的数据,如下所示:

DECLARE @input XML = '<License xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

<Reference>00b2d4cf-699c-4427-bcf0-a0ca456654c2</Reference>
 <MacAddresses>
  <string>00:0D:87:FE:9A:21</string>
  <string>00:20:ED:14:47:64</string>
  <string>00:13:D3:11:7C:D2</string>
  <string>00:13:D3:11:7C:D8</string>
  <string>00:19:D1:04:12:98</string>
  <string>00:19:66:C0:7F:AF</string>
 </MacAddresses>
</License>'

SELECT
    Reference = License.value('(Reference)[1]', 'varchar(50)'),
    MacAddress = MacAddr.value('.', 'varchar(50)')
FROM
    @input.nodes('License') AS XTbl1(License)
CROSS APPLY
    License.nodes('MacAddresses/string') AS XTbl2(MacAddr)

给出以下输出:

Reference                              MacAddress
00b2d4cf-699c-4427-bcf0-a0ca456654c2   00:0D:87:FE:9A:21
00b2d4cf-699c-4427-bcf0-a0ca456654c2   00:20:ED:14:47:64
00b2d4cf-699c-4427-bcf0-a0ca456654c2   00:13:D3:11:7C:D2
00b2d4cf-699c-4427-bcf0-a0ca456654c2   00:13:D3:11:7C:D8
00b2d4cf-699c-4427-bcf0-a0ca456654c2   00:19:D1:04:12:98
00b2d4cf-699c-4427-bcf0-a0ca456654c2   00:19:66:C0:7F:AF

当然,你也可以使用INSERT INTO dbo.YourTable(Reference, MacAddress) ....beforeSELECT自动将这些数据插入到表中

于 2013-05-20T16:08:32.473 回答