I wan...">

How to get item type in xpath?

My xml:

<record> <field name="f1"/> <id name="f2"/> <id name="f3"/> <field name="f4"/> <info/> </record> 

I want to skip it in xquery as follows:

 for $i in $records/record/field | $records/record/id return if ( .... $i is id .... ) then .... do something .... else ... do something else ... 

Is it possible? How to distinguish when $i is id and when is this field?

+4
source share
6 answers

Another neat XQuery solution is to use typeswitch:

 for $i in $records/record/field | $records/record/id return typeswitch($i) case element(id) return ... case element(field) return ... default return ... 
+4
source

Instead of trying with name () or local-name (), I would use self :: id, for example.

 if ($i[self::id]) then ... else ... 
+1
source

You can use the function library or create your own custom function. Something like that:

 for $i in $records/record/field | $records/record/id return if (name($i)="id") then .... do something .... else ... do something else ... 

http://www.xqueryfunctions.com/xq/fn_name.html

0
source

Check out the local-name function of XQuery - see MSDN docs here .

Given a set of node or node, it should give you the name node - the name of the tag. I assume you are looking, right?

eg. if you do this:

 DECLARE @input XML = '<record> <field name="f1"/> <id name="f2"/> <id name="f3"/> <field name="f4"/> <info/> </record>' SELECT inp.nod.query('local-name(.)') FROM @input.nodes('//*') AS inp(nod) 

You will get the following output:

 record field id id field info 
0
source

How about something simpler and more XQuery-like

 for $i in $records/record/field return do something with field, for $i in $records/record/id return do something with id 

In this case, the values โ€‹โ€‹returned first will be combined with the values โ€‹โ€‹from the 2nd for.

0
source

Use the arrow buttons:

 let $record := <record> <field name="f1"/> <id name="f2"/> <id name="f3"/> <field name="f4"/> <info/> </record> for $e in $record/* return typeswitch ($e) case element(id) return concat("id",$e/@name) case element (field) return concat("field",$e/@name) default return "other" 
0
source

Source: https://habr.com/ru/post/1303205/


All Articles