So i have an XML file which looks like below
declare @xml
xml= '<ENVELOPE>
<BILLFIXED>
<BILLDATE>29-Jun-2019</BILLDATE>
<BILLREF>123</BILLREF>
<BILLPARTY>ABC</BILLPARTY>
</BILLFIXED>
<BILLOP>200</BILLOP>
<BILLCL>200</BILLCL>
<BILLDUE>29-Jun-2019</BILLDUE>
<BILLOVERDUE>1116</BILLOVERDUE>
<BILLFIXED>
<BILLDATE>30-Jun-2019</BILLDATE>
<BILLREF>April To June -19</BILLREF>
<BILLPARTY>efg</BILLPARTY>
</BILLFIXED>
<BILLOP>100</BILLOP>
<BILLCL>100</BILLCL>
<BILLDUE>30-Jun-2019</BILLDUE>
<BILLOVERDUE>1115</BILLOVERDUE>
</ENVELOPE>
Im trying to read this using openxml
DECLARE @hDoc AS INT, @SQL NVARCHAR (MAX)
EXEC sp_xml_preparedocument @hDoc OUTPUT, @XML
select BILLDATE, BILLREF, BILLPARTY, BILLOP,BILLCL,BILLDUE, BILLOVERDUE
from OPENXML(@hDoc, '//BILLFIXED')
WITH
(
BillDate [varchar](50) 'BILLDATE',
BIllREF [varchar](50) 'BILLREF',
BILLPARTY [varchar](100) 'BILLPARTY'
,BILLOP [varchar](100) 'BILLOP'
BILLCL[varchar](100) 'REFERENCE',
BILLDUE [varchar](100) 'BILLDUE',
BILLOVERDUE [varchar](100) 'BILLOVERDUE'
)
It was easy to extract <BILLFIXED> tag but not able to access the siblings tags
<BILLCL>
<BILLDUE>
<BILLOVERDUE>
any help in accessing these tags Thanks
I agree you should not use
OPENXML, and instead use.nodesand.value.Unfortunately, SQL Server does not allow the
sibling::axis in XQuery, which would have made this much easier.You can do this purely using XQuery, by using the
>>positional predicate.What this does is as follows:
/ENVELOPE/BILLFIXEDnodes.$i.$i, so[. >> $i][1]db<>fiddle
If some of the nodes could be empty or missing, then you also need to check that the sibling node is before the next
BILLFIXEDnodedb<>fiddle
One final option is to transform the XML into a more normalized structure, and then query that
db<>fiddle
Steps are as follows:
.queryto create a new XML document.BILLFIXEDnode, store that in$bfBILLFIXEDnode which follows$bfin$nxtENVELOPEnode, containing$bfas well as all nodes which...$bf$nxtif there is a$nxt.nodes