Conditional Xpath?

ikantspelwurdz

Well-known member
Joined
Dec 8, 2009
Messages
49
Programming Experience
1-3
This isn't really a VB question, more of an XML question.

Suppose this XML document:
VB.NET:
<Root>
<Gender>Male</Gender>
<Name>Bill Gates</Name>
<BirthName>William Gates</BirthName>
</Root>

And this one:
VB.NET:
<Root>
<Gender>Female</Gender>
<Name>Melinda Gates</Name>
<BirthName>Melinda Ann French</BirthName>
</Root>

I want an XPath syntax that will retrieve the value of 'Name' for males, and 'BirthName' for females. This will always be determinable from the XPath address \Root\Gender, and will always be Male or Female.

Can this be done with XPath syntax? It's the equivalent of having code that does this:
VB.NET:
        Dim gender As String = doc.XPathSelectElement("\Root\Gender").Value
        If gender = "Male" Then
            Return doc.XPathSelectElement("\Root\Name").Value
        ElseIf gender = "Female" Then
            Return doc.XPathSelectElement("\Root\BirthName").Value
        End If

But instead I want it to look like this:
VB.NET:
Dim magicXPath as String = '???
Return doc.XPathSelectElement(magicXPath).Value
 
Selecting the element where other element (or attribute) has some value is done like this:
/Root[Gender='Male']/Name
Meaning: Select Name element that is child of Root element that has a Gender element with value "Male".

Then you can combine multiple xpath expressions with | operator (meaning like bitwise OR - a union).

Try to combine these two pieces of information to create your expression.

Recommended reading: XPath Tutorial
 
Back
Top