如果节点不存在,XPath 返回默认值 [英] XPath to return default value if node not present

查看:43
本文介绍了如果节点不存在,XPath 返回默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一对 XML 文档

Say I have a pair of XML documents

<Foo>
    <Bar/>
    <Baz>mystring</Baz>
</Foo>

<Foo>
    <Bar/>
</Foo>

我想要一个 XPath(仅限 1.0 版),它为第一个文档返回mystring",为第二个文档返回not-found".我试过

I want an XPath (Version 1.0 only) that returns "mystring" for the first document and "not-found" for the second. I tried

(string('not-found') | //Baz)[last()]

但联合的左侧不是节点集

but the left hand side of the union isn't a node-set

推荐答案

在 XPath 1.0 中,使用:

In XPath 1.0, use:

concat(/Foo/Baz,
       substring('not-found', 1 div not(/Foo/Baz)))

如果要处理可能的空 Baz 元素,请使用:

If you want to handle the posible empty Baz element, use:

concat(/Foo/Baz,
       substring('not-found', 1 div not(/Foo/Baz[node()])))

使用此输入:

<Foo>
    <Baz/>
</Foo>

结果:not-found 字符串数据类型.

Result: not-found string data type.

这篇关于如果节点不存在,XPath 返回默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆