日期:2014-05-18  浏览次数:20547 次

解析xml文件的问题
我有个xml文件,大概如下:
<ROOT>
<TABLE>
<tr>
<td>1111</td>
<td>2222</td>
<td>ASDF</td>
</tr>
<tr>
<td>5678</td>
<td>KJLI</td>
<td>6HJ</td>
</tr>
</TABLE>
</ROOT>
想解析为一个表单的数据
1111,2222,ASDF
5678,KJLI,6HJ

请问sp_xml_preparedocument之后可以做到么?
如果信息不够,添加类似<TABLE row="2" col="3">的信息来标示行*列的数量,这样可以么?
谢谢大家

------解决方案--------------------
SQL code

DECLARE @idoc INT
DECLARE @doc NVARCHAR(4000);  
SET @doc= 
'
<?xml version="1.0" encoding="UTF-16" ?>
<ROOT>
<TABLE>
<tr>
    <td>1111</td>
    <td>2222</td>
    <td>ASDF</td>
</tr>
<tr>
    <td>5678</td>
    <td>KJLI</td>
    <td>6HJ</td>
</tr>
</TABLE>
</ROOT>
' 

EXEC sp_xml_preparedocument @idoc OUTPUT, @doc 

;WITH base AS 
(
    SELECT * FROM OPENXML (@idoc,'/ROOT/TABLE',2) 
)
SELECT t.id AS rowid,t.localname,c.text,p.id AS colid
INTO #tmp
FROM base p INNER JOIN base c
ON p.id=c.parentid
INNER JOIN 
(
    SELECT DISTINCT id,localname
    FROM base
    WHERE localname='tr'
)t
ON p.parentid=t.id
WHERE c.text IS NOT NULL

;WITH base AS 
(
    SELECT * ,ROW_NUMBER() OVER(PARTITION BY rowid ORDER BY colid) AS rn
    FROM #tmp
)
SELECT distinct t1.rowid,convert(varchar,t1.text) AS col1,convert(varchar,t2.text) AS col2,convert(varchar,t3.text) AS col3
FROM base t1 
INNER JOIN base t2 
ON t1.rowid=t2.rowid
INNER JOIN base t3
ON t1.rowid=t3.rowid
WHERE t1.rn=1
AND t2.rn=2
AND t3.rn=3

EXEC   sp_xml_removedocument   @idoc 
DROP TABLE #tmp;