xpath find if node exists

匿名 (未验证) 提交于 2019-12-03 08:57:35

问题:

Using a xpath query how do you find if a node (tag) exists at all?

For example if I needed to make sure a website page has the correct basic structure like /html/body and /html/head/title

回答1:

...

so for example

body node existsbody node missing


回答2:

Try the following expression: boolean(path-to-node)



回答3:

Patrick is correct, both in the use of the xsl:if, and in the syntax for checking for the existence of a node. However, as Patrick's response implies, there is no xsl equivalent to if-then-else, so if you are looking for something more like an if-then-else, you're normally better off using xsl:choose and xsl:otherwise. So, Patrick's example syntax will work, but this is an alternative:

body node existsbody node missing


回答4:

Might be better to use a choice, don't have to type (or possibly mistype) your expressions more than once, and allows you to follow additional different behaviors.

I very often use count(/html/body) = 0, as the specific number of nodes is more interesting than the set. For example... when there is unexpectedly more than 1 node that matches your expression.



回答5:

I work in Ruby and using Nokogiri I fetch the element and look to see if the result is nil.

require 'nokogiri'  url = "http://somthing.com/resource"  resp = Nokogiri::XML(open(url))  first_name = resp.xpath("/movies/actors/actor[1]/first-name")  puts "first-name not found" if first_name.nil? 


回答6:

A variation when using xpath in Java using count():

int numberofbodies = Integer.parseInt((String) xPath.evaluate("count(/html/body)", doc)); if( numberofbodies==0) {     // body node missing } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!