Count number of elements with a given attribute

This should cover W3C XML Schema, Relax NG and DTD related problems.
mlcook
Posts: 67
Joined: Thu Jan 24, 2008 4:52 pm

Count number of elements with a given attribute

Post by mlcook »

In my xml file, I have several elements of the form (with contents omitted):

<Msg Id="100" Direction="Send"/>
<Msg Id="200" Direction="Send"/>
<Msg Id="300" Direction="Receive"/>
<Msg Id="400" Direction="Receive"/>

I'd like to count the number of nodes with Direction="Send", and count the number of nodes with Direction="Receive".

I can count the number of nodes, but I'd like to count based on the attribute Direction.

More specifically, I'd like to detect the break in the direction sequence, and do something special when direction changes from Send to Receive (just once, not at each Receive node).

Thanks for suggestions.
-- Mike
jkmyoung
Posts: 89
Joined: Mon Mar 06, 2006 10:13 pm

Re: Count number of elements with a given attribute

Post by jkmyoung »

What are you using to process the xml? xslt?

If you can use xpath, then the queries are:
"count(//Msg[@Direction='Send'])"
"count(//Msg[@Direction='Receive'])"

Also, if you're using xslt, you can have a special if clause when processing the first Receive
<xsl:template match="Msg[@Direction='Receive']">
<xsl:if test="not(preceding::Msg[@Direction='Receive'])">
do something special here
</xsl:if>
...

If you're using some sort of DOM, then when you're processing the message nodes with Direction Receive, (say node msg)

var checkFirst = msg.SelectSingleNode("preceding::Msg[@Direction='Receive']");
if (checkFirst == null)
do something special here.
Last edited by jkmyoung on Tue Feb 19, 2008 9:03 pm, edited 1 time in total.
mlcook
Posts: 67
Joined: Thu Jan 24, 2008 4:52 pm

Re: Count number of elements with a given attribute

Post by mlcook »

Yes, I'm using xslt to process the xml.

Your solution, count(//Msg[@Direction='Send']), was just what I needed.

I've read about XPath axes, etc., but must not have seen enough examples, nor assimilated the general idea, so thanks for pointing me in this direction.

-- Mike
Post Reply