Arsen Zahray
Arsen Zahray

Reputation: 25287

How to check for multiple attributes in 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?

Upvotes: 7

Views: 8488

Answers (1)

BoltClock
BoltClock

Reputation: 723388

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);
}

Upvotes: 8

Related Questions