Re: [xml] noob xpath question



On Wed, 2007-02-28 at 12:43 -0500, Stefan Jeglinski wrote:
There's likely a better list for this, but I've been spending 
most/all of my time at xmlsoft.org. I'm teaching myself xml, and I 
must be braindead - I just can't get past this one.

I've got xmllib2 compiled, and can compile and run a variety of the 
test code examples. I'm trying to get my head around xpath. Here is 
my toy xml file:

<?xml version="1.0" standalone="yes"?>
<!DOCTYPE myroot [
<!ELEMENT myroot (myelement+)>
<!ELEMENT myelement (x,y)>
<!ATTLIST myelement type (a | b) #REQUIRED>
<!ELEMENT x (#PCDATA)>
<!ELEMENT y (#PCDATA)>
]>
<myroot>
      <myelement type="a">
              <x>1a</x>
              <y>2a</y>
      </myelement>
      <myelement type="b">
              <x>1b</x>
              <y>2b</y>
      </myelement>
</myroot>


Using the xpath1.c sample code, I can successfully find element 
nodes, but I can't "subselect" based on type. for example, this xpath:

      /myroot/myelement/@type

returns 2 type nodes (as expected?), but no matter what syntax I've 
tried (I've googled, looked in books), I cannot select type a or b by 
itself, for example with umpteen variants of something along these 
lines:

      /myroot/myelement/@type[.='a']

I suspect I'm barking up the wrong tree (not to pun). Am I misusing 
xpath, probably on several levels? Have I missed a really dumb step 
in building the xml file to begin with? Other? Ultimately I want to 
be able to specify one element alone in the xml document using xpath 
- it's not so much that any final implementation will work like 
this... I just want to understand it.

I think what you want is this: /myroot/myelement[ type="a"]

here is a simple python program to play with:

#!/usr/bin/env python

import libxml2

str_doc = '''<?xml version="1.0" standalone="yes"?>
<myroot>
        <myelement type="a">
                <x>1a</x>
                <y>2a</y>
        </myelement>
        <myelement type="b">
                <x>1b</x>
                <y>2b</y>
        </myelement>
</myroot>
'''

xpath_expr = '/myroot/myelement[ type="a"]'

doc = libxml2.parseDoc(str_doc.strip())
root_node = doc.getRootElement()
context = doc.xpathNewContext()
context.setContextNode(root_node)
elements = context.xpathEval(xpath_expr)
print "'%s' expression returned %s" % (xpath_expr, elements)

-- 
John Dennis <jdennis redhat com>

Learn. Network. Experience open source.
Red Hat Summit San Diego  |  May 9-11, 2007
Learn more: http://www.redhat.com/promo/summit/2007





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