tags:

views:

87

answers:

2

I'm trying to loop through this XML to get specifically to the count fields.

What's the most efficient way to do this? I don't mind using libraries as long as they don't require root access to install since I'm on shared hosting. Is using libraries supposed to be a better practice or the opposite?

<category>
  <name>Category 1</name>
  <subcategories>
      <subcategory>
          <name>Subcategory 1.1</name>
          <count>18</count>
      <subcategory>
      <subcategory>
          <name>Subcategory 1.2</name>
          <count>29</count>
      <subcategory>
  <subcategories>
<category>

<category>
  <name>Category 2</name>
  <subcategories>
      <subcategory>
          <name>Subcategory 2.1</name>
          <count>18</count>
      <subcategory>
      <subcategory>
          <name>Subcategory 2.2</name>
          <count>29</count>
      <subcategory>
  <subcategories>
<category>
+3  A: 

Doing a simple XPATH query, you can get all count tags with one sentence. Provided the library you are using to access/parse the XML provides you with an XPATH API.

A simple python example (inspired in this SO question) could by:

import libxml2

doc = libxml2.parseFile("tst.xml")
ctxt = doc.xpathNewContext()
res = ctxt.xpathEval("count")
// do something with res here (should contain count nodes)
doc.freeDoc()
ctxt.xpathFreeContext()

Since you've just added PHP to the question, here is a LINK on how to do XPATH on PHP.

Pablo Santa Cruz
You beat me to this : )But stacker really needs to add a root element to his/her XML sample, and then use something like //subcategory/count
funkymushroom
+2  A: 

I use Linq to XML. However the fact that you've not stated your development platform makes it impossible to answer.

Chris
True. If you're on .NET 3, LinqToXML will be even better (IMHO) than XPATH.
Pablo Santa Cruz