Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check for multiple attributes in XPath?

Tags:

c#

xml

xpath

I'd like to select stylesheets in an XHTML document, which contain not only description, but also href.

For example

<link rel="stylesheet" href="123"/> 

should be selected, and

<link rel="stylesheet"/>  

should not.

At present, I'm doing it like this:

foreach (XmlNode n in xml.SelectNodes(@"//link[@rel='stylesheet']"))
{
    if (n.Attributes["href"]==null||n.Attributes[""].Value==null)
    {
        continue;
    }
    var l = Web.RelativeUrlToAbsoluteUrl(stuffLocation, n.Attributes["href"].Value);
}

but I suspect there's a much better way of doing this. Is there?

like image 308
Arsen Zahray Avatar asked Jan 23 '12 12:01

Arsen Zahray


People also ask

How do you locate multiple elements with the same XPath?

If an xpath refers multiple elements on the DOM, It should be surrounded by brackets first () and then use numbering. if the xpath refers 4 elements in DOM and you need 3rd element then working xpath is (common xpath)[3].

Which XPath syntax is correct to identify a web element using multiple attributes?

You can locate a web element by using its multiple attribute using "and" and "or".

Can we combine 2 Xpaths?

Use following or preceding Advanced Xpath to combine the two xpath.


1 Answers

Add and @href to the attribute expression:

//link[@rel='stylesheet' and @href]

This should allow you to omit the check altogether:

foreach (XmlNode n in xml.SelectNodes(@"//link[@rel='stylesheet' and @href]"))
{
    var l = Web.RelativeUrlToAbsoluteUrl(stuffLocation, n.Attributes["href"].Value);
}
like image 170
BoltClock Avatar answered Sep 22 '22 09:09

BoltClock