Get xml attribute values as string[]
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.
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);
You can make use of XmlNodeList class. You need to pass proper XPATH to fetch the values and iterate through the list.
精彩评论