How to extract leaf nodes from Oracle XMLTYPE
Question
I want to extract only the leaf nodes from an XMLTYPE object in Oracle 10g
SELECT
t.getStringVal() AS text
FROM
TABLE( XMLSequence(
XMLTYPE(
'<xml>
<node>
<one>text</one>
</node>
<node>
<two>text</two>
</node>
<node>
<three>text</three>
</node>
</xml>'
).extract( '//*' )
) ) t
What should I use as the WHERE clause so this returns only these:
<one>text</one>
<two>text</two>
<three>text</three>
I've tried the following but they don't work:
WHERE t.existsNode( '//*' ) = 0
WHERE t.existsNode( '/.//*' ) = 0
WHERE t.existsNode( './/*' ) = 0
What am I missing?
Solution
Nevermind, I found it:
WHERE
t.existsNode( '/*//*' ) = 0
OTHER TIPS
The XPath //*[not(*)]
will get any element at level 1 or deeper that does not have any children:
Query 1:
SELECT t.getStringVal()
FROM TABLE(
XMLSEQUENCE(
XMLTYPE(
'<xml>
<node><one>text</one></node>
<node><two>text</two></node>
<node><three>text</three></node>
</xml>'
).extract( '//*[not(*)]' )
)
) t
| T.GETSTRINGVAL() |
|---------------------|
| <one>text</one> |
| <two>text</two> |
| <three>text</three> |
If you want to be able to include the root element then use the XPath (//*|/*)[not(*)]
You can try the following PL/SQL:
DECLARE
x XMLType := XMLType(
'<?xml version="1.0" ?>
<xml>
<node>
<one>text</one>
</node>
<node>
<two>text</two>
</node
<node>
<three>text</three>
</node>
</xml>');
BEGIN
FOR r IN (
SELECT ExtractValue(Value(p),'/XML/node/one/text()') as one_x
,ExtractValue(Value(p),'/XML/node/two/text()') as TWO_x
,ExtractValue(Value(p),'/XML/node/three/text()') as three
FROM TABLE(XMLSequence(Extract(x,'/XML/node/'))) p
) LOOP
/* do whatever you want with r.one_x, r.TWO_x, r.three_x */
END LOOP;
END;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow