Method not reading XML attributes
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?
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()
Try this
string[] keywords =
XElement.Load(filename )
.Elements("Keyword" ) // not "Keywords"
.Attributes("name" )
.Select(n => n.Value)
.ToArray();
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.
精彩评论