I need to retrieve the attributes of the main node, but my code is not printing anything.
<MAINNODE AONE="22 11 12" ATWO="444"><CHILDNODE Aone="7"/></MAINNODE>
This is the code:
var listItems = xdocument.Root
.Elements("MAINNODE")
.Select(e => e.Attribute("AONE"))
.Select(a => a.Value.Split(' ').Select(s => XmlConvert.ToInt32(s)).ToList())
.ToList();
foreach (List<int> list in listItems)
{
print(list);
}
I am able to get attributes of child nodes, but not of the main one. I am new to LINQ and XML.
If this is the whole XML, then Root is the main node and you can get its attributes through xdocument.Root.Attributes
:
string[] listItems = xdocument.Root.Attribute("AONE").Value.Split();
int[] intItems = Array.ConvertAll(listItems, s => Int32.Parse(s));
foreach (int i in intItems) {
Console.WriteLine(i);
}
This will print
22
11
12
See also: Array.ConvertAll<TInput,TOutput>(TInput[], Converter<TInput,TOutput>) Method
Note: if you need a list, you can create one from the int[] intItems
array
var list = new List<int>(intItems);
or, instead of converting the string array to an int array first, directly do the conversion when calling the constructor:
var list = new List<int>(listItems.Select(s => Int32.Parse(s)));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.