我需要将XML文件中的属性插入到SQL表中。我已经在Stackoverflow上漫游以找到解决方案,但是我尝试过的任何方法似乎都没有效果。
我尝试了是否定义和使用命名空间,以及是否使用了各种不同的节点路径组合来浏览XML。
这是Xml的一部分,我想从以下位置检索属性:
``<export xmlns="http://www.arcticgroup.se/tariff/arctictariff/export" xmlns:at="http://www.arcticgroup.se/tariff/arctictariff/export" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.arcticgroup.se/tariff/arctictariff/export GoodsNomenclature.xsd ">
<id>e37c6378-892a-4c25-b3fe-d0f3fcdf5a29</id>
<exportType>GoodsNomenclatureObject</exportType>
<parameters />
<items>
<goodsNomenclature at:goodsNomenclatureCode="0101109090" at:dateEnd="2011-06-30" at:national="0" at:productLineSuffix="80" at:SID="74778" at:dateStart="2002-01-01" at:statisticalIndicator="0" at:changeType="U">
<goodsNomenclatureIndent at:national="0" at:quantityIndents="03" at:SID="74084" at:dateStart="2002-01-01" />
<goodsNomenclatureDescriptionPeriod at:national="0" at:SID="92833" at:dateStart="2002-01-01">
<goodsNomenclatureDescription at:description="andere" at:languageId="NL" at:national="0" />
<goodsNomenclatureDescription at:description="Other" at:languageId="EN" at:national="0" />
</goodsNomenclatureDescriptionPeriod>
</goodsNomenclature>
</items>
</export>``
这是我尝试的最后一个代码:
INSERT INTO TblGoodsNomenclature(XMLData, CreatedDate)
SELECT Convert(Xml, BulkColumn) as BulkColumn, GETDATE()
FROM OPENROWSET(Bulk '\\shareapp\c$\temp\GoodsNomenclature.xml', Single_Blob) as x;
DECLARE @XML AS XML, @hDoc AS INT, @SQL NVARCHAR (MAX)
SELECT @XML = XmlData FROM TblGoodsNomenclature
EXEC sp_xml_preparedocument @hDoc OUTPUT, @XML, '<export xmlns="http://www.arcticgroup.se/tariff/arctictariff/export" xmlns:at="http://www.arcticgroup.se/tariff/arctictariff/export"/>'
INSERT INTO NomenclatureCodes (NomenclatureCode, Description, DescriptionLanguage)
SELECT NomenclatureCode, Description, DescriptionLanguage
FROM OPENXML(@hDoc, '/items/goodsNomenclature/goodsNomenclatureDescriptionPeriod/goodsNomenclatureDescription/at:node')
WITH
(
NomenclatureCode INT '@at:goodsNomenclatureCode',
Description [varchar](100) '@at:description',
DescriptionLanguage [varchar](5) '@at:languageID'
)
我现在得到的结果只是一个空表,没有错误消息。我想要的是表中的“ goodsNomeclatureCode”,“ description”和“ languageID”。
答案 0 :(得分:1)
如评论中所述,您最好在这里使用XQUERY。由于您还有多个名称空间,因此我们也需要声明它们。这将为您提供以下查询:
WITH XMLNAMESPACES (DEFAULT 'http://www.arcticgroup.se/tariff/arctictariff/export',
'http://www.arcticgroup.se/tariff/arctictariff/export' AS [at])
SELECT GN.XMLData,
EI.gN.value('@at:goodsNomenclatureCode[1]','varchar(15)') AS goodsNomenclatureCode
FROM dbo.TblGoodsNomenclature GN
CROSS APPLY GN.XMLData.nodes('export/items/goodsNomenclature') EI(gN);