How to convert xml text stored in a VARCHAR and se

2019-08-17 10:44发布

问题:

I have xml documents stored as text in a VARCHAR column. I'd like to convert the text to XML documents in order to perform XQUERY selects on the documents.

An example document looks like:

<a>
   <b foor="bar"/>
   <c/>
</a>

My query looks like:

SELECT XMLQUERY('//c' PASSING 
  XMLCAST('<a><b foor="bar"/><c/></a>' AS XML)) 
FROM SYSIBM.sysdummy1

But instead of returning a element I get the following error message:

SQL Error [10507]: The Context item in an axis step must be a node. SQLCODE=-16012, SQLSTATE=10507

How can I get this to work?

===========================================
Update #1: Just in case anyone stumbles upon the same problem. At least in my environment the queries below work but instead of returning the text of the matching xml nodes I only got columns showing up as value "[le]". I had to cast the result to e.g. VARCHAR XMLCAST() to get the xml as text. So I changed Stavr00's query to:

SELECT 
    XMLCAST(XMLQUERY('string(/a/b/@foo)' PASSING X) AS VARCHAR(20)) 
FROM (
SELECT xmlparse('<a><b foo="bar"/><c/></a>')
FROM sysibm.sysdummy1
) AS X(X)

回答1:

Agree with @data_henrik. However I recommend using CTE nesting as to parse XML only once:

SELECT 
    XMLQUERY('string(/a/b/@foo)' PASSING X) 
   ,XMLQUERY('//c' PASSING X)
FROM (
SELECT xmlparse('<a><b foo="bar"/><c/></a>')
FROM sysibm.sysdummy1
) AS X(X)


回答2:

Not syntax-tested below, but I recommend to use XMLPARSE. It converts the string into XML which can be used by XMLQUERY:

SELECT XMLQUERY('//c' PASSING 
        xmlparse(document '<a><b foor="bar"/><c/></a>'))
FROM sysibm.sysdummy1

That should return <c/>.



标签: sql db2