tags:

views:

218

answers:

2

My xml file has something like this:
...
<Keyword name = "if" />
<Keyword name = "else" />
<Keyword name = "is" />
...

So how can I recursively get all of the values of the name attribute and add them to a List<string> or string[]. Maybe a foreach loop?


I followed codemeit's and I keep getting an error:Data at the root level is invalid. Line 1, position 1. My xml file is
<KeyWords>
...
<KeyWord name = "if" />
...
</KeyWord>


New problem The '\' character, hexadecimal value 0x5C, cannot be included in a name. but the same file.

A: 

You can make use of XmlNodeList class. You need to pass proper XPATH to fetch the values and iterate through the list.

Vijay Balkawade
+5  A: 

Assume let variable testXml is equal to the follow xml string

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

Use XElement and LINQ to extract the name attribute values

var myXml = XElement.Parse(testXml );
var myArray = myXml.Elements().Where(n => n.Name.LocalName.Equals("Keyword"))
                    .Select(n => n.Attribute("name").Value)
                    .ToArray();

myArray will contain {"if", "else", "is"}

UPDATE

Thanks to @SLaks comment, we could actually just do

var myArray = myXml.Elements("Keyword").Attributes("name").Select(n => n.Value);
codemeit
This is really amazing.. I must learn LINQ now..
Vijay Balkawade
You should call `myXml.Elements("Keyword")`
SLaks