开发者

How do I make XPath expressions more generic?

I have xpath expressions for a navigation tree which contains some child branches whicjh can be added:

/html/body/div[@id='application-wrapper']/div/div[2]/div/div[3]/div/div[2]/div/div/div/div[3]/div/**div[1]**/div[1]开发者_运维技巧/table/tbody/tr/td[2]/div[@id='gwt-uid-17']/a

/html/body/div[@id='application-wrapper']/div/div[2]/div/div[3]/div/div[2]/div/div/div/div[3]/div/**div[2]**/div[1]/table/tbody/tr/td[2]/div[@id='gwt-uid-58']/a

/html/body/div[@id='application-wrapper']/div/div[2]/div/div[3]/div/div[2]/div/div/div/div[3]/div/**div[3]**/div[1]/table/tbody/tr/td[2]/div[@id='gwt-uid-83']/a

i need to make it generic statement similar to the given below but unable to do it

//div[@role='treeitem']/a[text()='Situation']/ancestor::table//div[1]//a

Can some one shed some light?

Update from comments

I can see 3 child nodes[ div[1] in first expression, div[2] in second expression and div[3] in third expression] so instead of writing till div[100] i want to put it as div[%d] but I am unable to do so


If the values of the id attributes uniquely identify the elements, then a short expression that selects exactly all these three a elements is:

//div[@id='gwt-uid-17' or @id='gwt-uid-58' or @id='gwt-uid-83']/a

However, evaluating the // abbreviation can be very inefficient and is not recommended.

A single XPath expression that select these three a elements and will be more efficient is:

/html/body/div[@id='application-wrapper']/div/div[2]/div/div[3]
   /div/div[2]/div/div/div/div[3]/div/div[not(position() >3)]/div[1]
    /table/tbody/tr/td[2]
     /div[@id='gwt-uid-17' or @id='gwt-uid-58' or @id='gwt-uid-83']/a


Assuming that this is valid XHTML, and that id is actually a unique identifier, you don't need any of the hierarchy above the specified divs, and can use an XPath expressions like this:

//div[@id='gwt-uid-17']/a

Depending on your language binding, you can also use variables in your XPath expressions, so could use a generic expression like this:

//div[@id='$theDivIWant']/a


All you need is the shortest expression that uniquely identifies the node(s) you want. For example, the expression

//div[@id='gwt-uid-17']/a

is equivalent to the first line above, because ids are unique (supposedly).

If you want to target links under the "Situation" link, you can try

//a[text()='Situation']//table//a[1]

but I'd need to see the XML to know if that's correct.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜