DOM navigation

Given an XML document loaded as a DOM structure, I'd like to iterate over all grandchildren whose ancestors match certain conditions, and I'd like to specify those conditions such that they can be easily modified. For example, in the syntax I've devised, iterate(document, "{a}{b}{c,type,int}{value}") will do something equivalent to
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
list = []
foreach child in document.children
    if child.name != "a"
        continue
    foreach child2 in child.children
        if child2.name != "b"
            continue
        foreach child3 in child2.children
            if child3.name != "c" || !child3.has_attribute("type") || child3.attribute("type") != "int"
                continue
            foreach child4 in child3.children
                if child4.name != "value"
                    continue
                list.add(child4)
return list
Does anyone know of something that does something like this? I'm not sure what to use for a search term.
You want to search for selectors.

W3schools gets a bad wrap, but it is a good starting point:
http://www.w3schools.com/xpath/xpath_syntax.asp

As a tip, selectors are typically calculated from the back:
1
2
3
4
5
6
7
8
9
10
11
12
foreach child4 in the whole document
  if child4.parent name is not c and it does not have a type int
    continue

  if child4.parent.parent.name is not b
     continue

  //...

  add child4 to list

//... 


I know that is how CSS works, but it does seem to defy all logic.
Last edited on
Thanks, that's pretty much what I was looking for.
Topic archived. No new replies allowed.