0

I have written this test code to read in a XSL data file and locate link elements:

using System;
using System.Xml.Linq;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                XName qualifiedName = XName.Get("link", "http://www.w3.org/1999/xhtml");
                XDocument doc = XDocument.Load("d:\\test.xsl");
                foreach (XElement element in doc.Descendants(qualifiedName))
                {
                    XAttribute attrRel = element.Attribute("rel");
                    XAttribute attrType = element.Attribute("type");
                    XAttribute attrHref = element.Attribute("href");

                    if (attrRel == null || attrType == null || attrHref == null)
                        continue;

                    if(attrRel.Value == "stylesheet" && attrType.Value == "text/css")
                        Console.WriteLine(attrHref.Value.ToString());
                }
            }
            catch(Exception e)
            {
                Console.WriteLine(e);
            }
        }
    }
}

It is working OK. The link elements are standard HTML. For example:

<link rel="stylesheet" type="text/css" href="Workbook-S-140-PublicTalk-WatchtowerStudy-ServiceTalk-Videoconference2.css"/>
<link rel="stylesheet" type="text/css" href="Workbook-S-140-PublicTalk-WatchtowerStudy-ServiceTalk-Zoom.css"/>

In the answer to my previous question they said about using XPath to locate all link nodes which have the attributes rel="stylesheet" and type="text/css". But I am trying with LINQ 2 XML and can't work this out.

At the moment I have done the tests manually.


I have since learned that I can simplify the above code like this:

var strRel = (string)element.Attribute("rel") ?? "";
var strHref = (string)element.Attribute("href") ?? "";
Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
  • 1
    I see this question https://stackoverflow.com/questions/2678251/find-elements-by-attribute-using-xdocument. Do I have to store the result of `Descendants` into an array and then use a `where` clause on that array? – Andrew Truckle Jan 17 '21 at 19:39
  • I suppose since this is my own code we can ignore the `type` attribute. So we are only interested in the other attributes. – Andrew Truckle Jan 17 '21 at 21:32

0 Answers0