Hi, Claudio.
Sample XML seems to me to be wrong.
In any case follow some tips with XML extraction. I hope they are helpful.
1- You do not need to know the quantity repeated elements to iterate between them. Using XMLTable syntax You can make a SELECT in XML quite simply as if it were a table
Select all
SELECT *
FROM Xmltable('det/prod' PASSING XMLTYPE('<det nItem = "4">
<prod>
<cprod>produto 1</cprod>
</prod>
<prod>
<cprod>produto 2</cprod>
</prod>
<prod>
<cprod>produto 3</cprod>
</prod>
<prod>
<cprod>produto 4</cprod>
</prod>
</det>') COLUMNS cprod VARCHAR2(4000) PATH 'cprod')
;
2- You really need to read an attribute of a tag, your query can be like this:
Select all
SELECT nitem
FROM xmltable('det' passing xmltype('
<det nItem = "4">
<prod>
<cprod>produto 1</cprod>
</prod>
<prod>
<cprod>produto 2</cprod>
</prod>
<prod>
<cprod>produto 3</cprod>
</prod>
<prod>
<cprod>produto 4</cprod>
</prod>
</det>') columns nItem VARCHAR2(4000) path '@nItem');
3- If XML has tags with values ??at different levels (parent and Son) You should use an XMLTable for each level.
To perform the junction between them use the XML itself extracted from the highest level:
Select all
SELECT nitem, cprod
FROM xmltable('det' passing xmltype('
<det nItem = "4">
<prod>
<cprod>produto 1</cprod>
</prod>
<prod>
<cprod>produto 2</cprod>
</prod>
<prod>
<cprod>produto 3</cprod>
</prod>
<prod>
<cprod>produto 4</cprod>
</prod>
</det>') columns nItem VARCHAR2(4000) path '@nItem'
,produtos XMLTYPE path '/') det,
Xmltable('det/prod' PASSING det.produtos COLUMNS cprod VARCHAR2(4000) PATH 'cprod')
I hope it helps!