views:

201

answers:

2

Hi Guys,

I am writing a small app that finds all the folders IIS is referencing.

To do this I take the IIS config file and parse the xml looking for elements called IIsWebVirtualDir and look for the Path attribute.

Here is my code

XDocument doc = XDocument.Load(xmlPath);

                IEnumerable<XElement> elements = doc.Elements();

                foreach (XElement element in elements)
                {
                    elementCount++;
                    foreach (XAttribute attribute in element.Attributes())
                    {
                        if(attribute.Name == "Path")
                        {
                            pathsFound++;
                            String path = attribute.Value + ",";
                            Console.WriteLine(path);
                            pathsAsStr.Append(path);
                        }
                    }
                }

I have also tried using IEnumerable elements = doc.Elements().Descendants("IIsWebVirtualDir");

The code compiles but I never find more than one element. Why is this? What am I doing wrong?

I would attach the xml but its too big

+1  A: 

Try something like this:

int elementCount = doc.Elements().Count();
var elementsWithPathAttribute = doc.Elements().Where(el => el.Attribute("Path") != null);

/*
    The non lamba version would be
    var elementsWithPathAttribute = from el in doc.Elements()
                                    where el.Attribute("Path") != null
                                    select el;
/*

foreach(XElement element in elementsWithPathAttribute)
{
   //do processing here.
}

Another way would be to do this:

using Syste.Xml.XPath;
using System.Xml.Linq;

//....

var elementsWithPathAttribute = 
    doc.Elements.XPathSelectElements("//*[@Path]")
Micah
thanks Micah - i tried the first method and I'm still getting the same problem. could this mean the xml is badly formed?I got it by using Save Configuration to file in IIS 6.0 for websites.
mancmanomyst
shoot me an email with the xml. micah over at codingcontext dot com. I'll take a look at it.
Micah
+1  A: 

How about:

var apps = from element in elements
           where element.Attributes["Path"] != null
           select element;

To retrieve all the elements you need. You now have an IEnumerable with the correct elements.

ck