Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use XPath to count the number of nodes with a certain attribute

Tags:

count

xpath

I can't seem to get an XPath expression to work for my scenario. I want to find all the "Device" nodes that have the type "EndDevice". I'm able to count all the "Device" nodes, and I'm also able to find all "Device" nodes with the "EndDevice" attribute. However, I can't seem to combine them!

count(//Device) //works //Device[@xsi:type='EndDevice'] //works count(//Device[@xsi:type='EndDevice']) //doesn't work 

If it matters, I'm using XPathBuilder.

like image 303
Jason Young Avatar asked Mar 05 '10 18:03

Jason Young


2 Answers

I reproduced it using XPathBuilder 2.0.0.4. However the XPath expression works and evaluates correctly in an online evaluator I tried (http://www.whitebeam.org/library/guide/TechNotes/xpathtestbed.rhtm).

EDIT: Also tried with latest version of Altova XMLspy

input:

<?xml version="1.0"?> <asdf xmlns:xsi="n/a">     <Device xsi:type='EndDevice'/>     <Device xsi:type='EndDevice'/>     <Device xsi:type='EndDevice'/>     <Device xsi:type='EndDevice'/> </asdf> 

xslt:

<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:xsi="n/a">     <xsl:output indent="yes"/>     <xsl:template match="*">         <output>             <xsl:value-of select="count(//Device[@xsi:type = 'EndDevice'])"/>         </output>     </xsl:template> </xsl:stylesheet> 

output:

<?xml version="1.0" encoding="UTF-8"?> <output xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:xsi="n/a">4</output> 

I think it's XPathBuilder thats doing something wrong.

like image 52
Ledhund Avatar answered Oct 11 '22 13:10

Ledhund


Using the above xml saved into a test.xml and using the tool http://kernowforsaxon.sourceforge.net/

declare namespace xsi="n/a";  count(doc('test.xml')//Device[@xsi:type = "EndDevice"]) 

Produces the right output.

like image 26
Xavier John Avatar answered Oct 11 '22 14:10

Xavier John