使用命名空间在SQL Server上读取Xml

时间:2012-08-27 15:59:09

标签: sql-server xml

我尝试使用本指南在SQL Server中读取XML文件。

http://blog.sqlauthority.com/2009/02/13/sql-server-simple-example-of-reading-xml-file-using-t-sql/

工作正常,但我有一个带有命名空间的XML文件,并且这个代码不能用于命名空间。

一些解决方案?


感谢Remus。现在我有了这段代码

 DECLARE @MyXML XML
SET @MyXML = '<cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3"   Moneda="USD">
    <cfdi:Impuestos totalImpuestosRetenidos="0.00" totalImpuestosTrasladados="1143.06">
    </cfdi:Impuestos>
</cfdi:Comprobante> ' 

;with xmlnamespaces('http://www.sat.gob.mx/cfd/3' as cfdi)
SELECT
a.b.value('@Moneda','varchar(100)') Moneda,
a.b.value('Impuestos[1]/@totalImpuestosTrasladados','float') totalImpuestosTraslados
FROM @MyXML.nodes('cfdi:Comprobante') a(b)

可以使用,但totalImpuestosTraslados的值为NULL。

Moneda totalImpuestosTraslados

USD NULL

3 个答案:

答案 0 :(得分:2)

使用WITH XMLNAMESPACES。如果此信息不足,请发布详细信息(您尝试过的内容,错误)。

答案 1 :(得分:0)

DECLARE @MyXML XML
SET @MyXML = '<cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3"   Moneda="USD">
    <cfdi:Impuestos totalImpuestosRetenidos="0.00" totalImpuestosTrasladados="1143.06">
    </cfdi:Impuestos>
</cfdi:Comprobante> ' 

;with xmlnamespaces('http://www.sat.gob.mx/cfd/3' as cfdi)
SELECT
a.b.value('@Moneda','varchar(100)') Moneda,
a.b.value('cfdi:Impuestos[1]/@totalImpuestosTrasladados','float') totalImpuestosTraslados
FROM @MyXML.nodes('cfdi:Comprobante') a(b)

答案 2 :(得分:0)

“Impuestos”也有cfdi作为命名空间,所以你也必须包含它

DECLARE @MyXML XML
SET @MyXML = '<cfdi:Comprobante xmlns:cfdi="http://www.sat.gob.mx/cfd/3"   Moneda="USD">
<cfdi:Impuestos totalImpuestosRetenidos="0.00" totalImpuestosTrasladados="1143.06">
</cfdi:Impuestos>
</cfdi:Comprobante> ' 

;with xmlnamespaces('http://www.sat.gob.mx/cfd/3' as cfdi)
SELECT
a.b.value('@Moneda','varchar(100)') Moneda,
a.b.value('<b>/cfdi:</b>Impuestos[1]/@totalImpuestosTrasladados','float') totalImpuestosTraslados
FROM @MyXML.nodes('cfdi:Comprobante') a(b)