开发者

Easiest way to read this XML

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>


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜