Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 641
  • Last Modified:

XPath -count no. of specific tag occurences

I am using libxml2 library in C to parse an xml document.  I am trying to count the no. of tags <Book>.  I tried using
"count(//Book)".  But I want the number rather than the node-set.   Is there an xpath expression to do this?

<?xml version="1.0" ?>
- <Book List>
- <Book>
  <Name>book1</Name>
  <Author>author1</Author>
  <Price>15.00</Price>  
  </Book>
- <Book>
  <Name>book2</Name>
  <Author>author2</Author>
  <Price>10.00</Price>  
  </Book>
  </Book List>

Thanks
0
inquisitive123
Asked:
inquisitive123
2 Solutions
 
PraesidiumCommented:
XmlNode[] full = new XmlNode[full.Count];

Seems like this should work for you, count the number of nodes in your node list...  Why do you want the number of nodes, because depending on what you are doing, I may be able to offer you a better alternative...
0
 
rdcproCommented:
Well, count(//Book) *is* an XPath eppression that does this.  Well, rather it's an XSLT expression that uses XPath.  But, I don't think there are any methods in Libxml that don't return nodesets...That is, in XSLT such an XPath expression will return a number but using DOM methods, it's not allowed.  You can get the nodelist, then use the DOM length property--this is the standard way of doing it.  I'm not a C programmer, but in Python (using the XPath wrappers for libxml2):

import libxml2

doc = libxml2.parseFile("tst.xml")
ctxt = doc.xpathNewContext()
res = ctxt.xpathEval("//book")
if len(res) != 2:
    print "XPath Query did not return the expected node set"
    sys.exit(1)
doc.freeDoc()
ctxt.xpathFreeContext()

Note that you must explicitly free both the document and the context.

Regards,
Mike Sharp
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now