user1195895
user1195895

Reputation: 41

count xml elements with multiple conditions

I have the following XML code, that I am trying to transform using an xlst:

<setting>
    <type>house</type>
    <context>roof</context>
    <value>blue</value>
</setting>
<setting>
    <type>house</type>
    <context>kitchen</context>
    <value>red</value>
</setting>
<setting>
    <type>house</type>
    <context>floor</context>
    <value>black</value>
</setting>
<setting>
    <type>apartment</type>
    <context>roof</context>
    <value>red</value>
</setting>

I want to count whether the setting->type "apartment" has a "context->floor".

I tried to do this with:

<xsl:if test="count(setting[type='apartment'] and setting[context='floor']) &lt; 1">
    <!-- do what ever !-->
</xsl:if>

but it doesn't seem to work. I get an exception about trying turning a number into a boolean? Any suggestions?

update: i figured out that i could use:

<xsl:if test="count(setting[type='apartment' and context='floor']) &lt; 1">

Upvotes: 4

Views: 11175

Answers (2)

Sean B. Durkin
Sean B. Durkin

Reputation: 12729

How about using cascaded predicates like thus?:

count(setting[type='apartment'][context='floor']) &lt; 1

Upvotes: 0

Pawel
Pawel

Reputation: 31610

The statement inside count is returning boolean value which is not correct. count() requires node-set to be able to count nodes. If this the same setting element that needs to have type and appartment elements with the required values the you are probably looking at:

count(setting[type='apartment' and context='floor']) &lt; 1

Otherwise if you need a sum of setting elements that have type=apartment or context=floor (excluding counting setting that has both elements with required values) you probably need:

count(setting[type='apartment'] | setting[context='floor']) &lt; 1

Upvotes: 2

Related Questions