具有绝对路径的xpath中的条件

时间:2015-12-11 10:17:47

标签: xml xpath

我正在尝试使用绝对路径并为我的XPath 1.0添加条件

<School>
<Category group = "red">
    <Teacher name = "john" Status = "Absent" />
    </Teacher>
</Category>
    <Category group = "Green">
    <Teacher name = "Smith" Status = "Present" />
</Category>

我希望实现的目标是:

if 
    /School/Category[@group = "Red"]/@Status = "Present"
then 
    /School/Category[@group = "Red"]/teacher/@name 
else
    /School/Category[@group = "Green"]/teacher/@name 

1 个答案:

答案 0 :(得分:0)

使用XPath 1.0,您可以这样做:

/School/Category[@group = 'red']/Teacher[@Status = 'Present']/@name 
    | 
/School[
    not(
        Category[@group = 'red']/Teacher[@Status = 'Present']
    )
]/Category[@group = 'Green']/Teacher/@name

union运算符(|)之前的XPath部分表示以下逻辑:

if 
    /School/Category[@group = "Red"]/@Status = "Present"
then 
    /School/Category[@group = "Red"]/teacher/@name 

......其余代表以下逻辑:

if not
    (/School/Category[@group = "Red"]/@Status = "Present")
then 
    /School/Category[@group = "Green"]/teacher/@name

<强> xpathtester demo

输出

Smith