Re: [xml] How to select a node based on attribute values?



On Tue, 2006-11-28 at 16:57 -0800, Yan Seiner wrote:
Fist off, I'm a total newbie when it comes to libxml.  I've been able to 
work my way through some examples, and produce working code, but I'm not 
entirely happy with the result, and I would like some advice.

I have an XML tree that looks like this:

<root>
    <plc id="1">
       <some stuff/>
    </plc>
    <plc id="2">
       <some other stuff/>
    </plc>
</root>

I have a relatively small number (< 50) of the plc nodes, but the whole 
tree is pretty big.

What is the best (or simplest way) to retrieve the information for plc 2?

xpath is the simplest and most powerful

Should I pull all of the plc elements using xmlXPathEvalExpression, and 
then iterate over them with xmlGetProp looking for an id attribute with 
a value of "2"?

no need to iterate, just create an xpath _expression_ which specifies id=2

off the top of my head the _expression_ would be "/plc[ id="2"]"

just google xpath syntax or xpath examples, you'll turn up a ton

libxml2 xpath example C code here: http://xmlsoft.org/examples/index.html#XPath

The xpath spec has examples too: http://www.w3.org/TR/xpath

If you're comfortable with python or another scripting language you can construct a simple test program to exercise your xpath syntax in about 5 minutes.
-- 
John Dennis <jdennis redhat com>


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]