tags:

views:

52

answers:

3

This method:

public static string[] getKeywords(string filename)
{
    string[] keywords = XElement.Load(filename).Elements("Keyword").Attributes("name").Select(n => n.Value).ToArray  
    return keywords;
}

Will not read the xml file. I have even tested every place it was called and it led back to getKeywords. I even tested it by

string[] test = getKeywords("APIs\\cmake.xml");
textbox.Text = test[0];

And I get an ArrayIndexOutOfBounds Exception. The xml file is accessable by this method. Just that it does not read the attribute. Here is a sample of the xml file:

<Keywords>
...
<Keyword name ="if" />
<Keyword name ="else" />
...
</Keywords>

What is wrong?

A: 

Try this

string[] keywords =
    XElement.Load(filename  )
        .Elements("Keyword" )  // not "Keywords"
        .Attributes("name"  )
        .Select(n => n.Value)
        .ToArray();
Rubens Farias
sorry, that was my typo
Mohit Deshpande
this code returned `{"if", "else"}` to me; its wrong?
Rubens Farias
A: 

You logic is slightly off. You need to use: XElement.Load(filename).Element("Keywords").Elements("Keyword").Select(n => n.Attributes("name")FirstOrDefault.value).ToArray

For each keyword node, it will return the value of the name attribute.

Patrick Karcher
+2  A: 

EDIT: The Elements("Keyword") call returns the an enumerable containing the all of the Keyword elements that are directly within the document root. Since there aren't any (the document root contains a single Keywords (plural) element), you're not getting any values.

You need to get all of the Keyword elements in the document, like this:

return XElement.Load(filename)
               .Descendants("Keyword")
               .Attributes("name")
               .Select(n => n.Value)
               .ToArray()

Alternatively, you can explicitly get all of the Keyword elements within the Keywords element, like this: (This will not get Keyword elements that are inside of other elements)

return XElement.Load(filename)
               .Element("Keywords")
               .Elements("Keyword")
               .Attributes("name")
               .Select(n => n.Value)
               .ToArray()
SLaks