65.9K
CodeProject 正在变化。 阅读更多。
Home

解决将 XML 传递到存储过程中遇到的问题

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.21/5 (5投票s)

2004年9月23日

viewsIcon

60415

在将 XML 传递到存储过程时遇到问题,因为存在命名空间?这个脚本可能会解决它。

引言

通常,当 XML 数据被传递到存储过程时,它会包含 XML 版本和编码信息以及命名空间声明。这有时会干扰 XPath 查询。这里有一种解决问题的方法。

假设 XML 如下

<?xml version="1.0" encoding="utf-8" ?> 
<MESSAGE xmlns="https://tempuri.org"> 
<HEADER> 
<TAG1>test</TAG1>
<TAG2></TAG2>
</HEADER>
<DETAILS>
<TAG1></TAG1>
<TAG2></TAG2>
</DETAILS>
</MESSAGE>

以及存储过程

create PROCEDURE ProcessXMLDocument

@xmlDoc varchar(8000)
AS
DECLARE @hDoc int
/*Load the document*/
EXEC sp_xml_preparedocument @hDoc OUTPUT, @xmlDoc
DECLARE @message varchar(10)

SELECT @message= [TAG1]
FROM OPENXML
(@hdoc,'//HEADER',2)
WITH 
(TAG1 varchar(10))

当这个 XML 传递到存储过程时,XPath 查询并不总是返回正确的结果。这个查询将不会返回任何内容。

以下代码将通过删除命名空间标签来解决问题

create PROCEDURE ProcessXMLDocument
@xmlDoc varchar(8000)
AS
-------------------------------------------------------------------------
DECLARE @hDoc int,
@NSEndPos int
-------------------------------------------------------------------------
/*Remove the xml declaration as it messes up the
  document use the first end tag (>) as the marker for text removal*/
-------------------------------------------------------------------------
Select @NSEndPos = PATINDEX('%>%', @xmldoc) +1
Select @xmldoc = Substring(@xmldoc,@NSEndPos,Len(@xmldoc) - @NSEndPos +1)
-------------------------------------------------------------------------
/*Remove the Namespace as it messes up the document use
  the first end tag (>) as the marker for text removal*/
-------------------------------------------------------------------------
Select @NSEndPos = PATINDEX('%>%', @xmldoc) +1
Select @xmldoc = '<MESSAGE>' + Substring(@xmldoc, 
                  @NSEndPos,Len(@xmldoc) - @NSEndPos +1) 
-------------------------------------------------------------------------
/*Load the document*/
EXEC sp_xml_preparedocument @hDoc OUTPUT, @xmlDoc
DECLARE @message varchar(10)

SELECT @message= [TAG1]
FROM OPENXML
(@hdoc,'//HEADER',2)
WITH 
(TAG1 varchar(10))

现在这将返回 'test'。

尽情享用!!

© . All rights reserved.