XPath expression with condition on multiple ancestors

Posted by Rest Wing on Stack Overflow See other posts from Stack Overflow or by Rest Wing
Published on 2011-02-12T22:07:03Z Indexed on 2011/02/12 23:25 UTC
Read the original article Hit count: 378

Filed under:
|
|

The application I am developing receives an XML structure similar to following:

<Root>
    <Valid>
        <Child name="Child1" />
        <Container>
            <Child name="Child2" />
        </Container>
        <Container>
            <Container>
                <Child name="Child3"/>
                <Child name="Child4"/>
            </Container>
        </Container>
        <Wrapper>
            <Child name="Child5" />
        </Wrapper>
        <Wrapper>
            <Container>
                <Child name="Child19" />
            </Container>
        </Wrapper>
        <Container>
            <Wrapper>
                <Child name="Child6" />
            </Wrapper>
        </Container>
        <Container>
            <Wrapper>
                <Container>
                    <Child name="Child20" />
                </Container>
            </Wrapper>
        </Container>
    </Valid>
    <Invalid>
        <Child name="Child7" />
        <Container>
            <Child name="Child8" />
        </Container>
        <Container>
            <Container>
                <Child name="Child9"/>
                <Child name="Child10"/>
            </Container>
        </Container>
        <Wrapper>
            <Child name="Child11" />
        </Wrapper>
        <Container>
            <Wrapper>
                <Child name="Child12" />
            </Wrapper>
        </Container>
    </Invalid>
</Root>

I need to get a list of of Child elements under following conditions:

  1. Child is n generation descendant of Valid ancestor.
  2. Child may be m generation descendant of Container ancestor which is o generation descendant of Valid ancestor.
  3. Valid ancestors for Child element are Container elements as m generation ancestors and Valid element as first generation ancestor.

where m, n, o are natural numbers.

I need to write following XPath expressions

Valid/Child
Valid/Container/Child
Valid/Container/Container/Child
Valid/Container/Container/Container/Child
...

as a single XPath expression.

For provided example, the XPath expression would return only Child elements having name attribute equal to Child1, Child2, Child3 and Child4.

The closest I have come to solution is following expression.

Valid/Child | Valid//*[self::Container]/Child

However, this would select Child element with name attribute equal to Child19 and Child20.

Does XPath syntax supports either optional occurrence of an element or setting condition similar to self in previous example to all ancestors between Child and Valid elements?

© Stack Overflow or respective owner

Related posts about c#

Related posts about Xml