Monday, February 21, 2011

How can I return a specific node when there are different selection criteria/depths with xpath?

Given the following XML,

<root>
    <property>
        <programs>
            <program>1</program>
            <program>5</program>
        </programs>
        <tool>
        </tool>
    </property>
    <property>
        <tool>
            <programs>
                <program>1</program>
                <program>2</program>
            </programs>
        </tool>
    </property>
</root>

how would I write an XPath expression to return a collection containing the "property" nodes when program=1? I think I want to write something like "give me all the property nodes when self or a descendant contains programs[program=1]", but can't get it to just give me the "property" nodes...

From stackoverflow
  • property[.//programs/program=1]
    

    Selects the property elements that contain descendant programs elements that contain a child program element who's value is 1.

    end-user : Aha! I knew there had to be a way to do it. "That was easy!" Thx
    Tomalak : You mean `property[.//programs/program=1]`. `//` starts at the root, which would lead to *every* property node being returned as long as there is a `program=1` anywhere in the document. `.//` starts at the context node.
    Mads Hansen : Doh! Thanks, Tomalak. I've corrected the answer

0 comments:

Post a Comment