Working with an XML currently
<Company>
<Employee>
<FirstName Initial="A" Totaldigits="six" Lastletter="T"/>
<FirstName Initial="A" Totaldigits="six" Lastletter="Y"/>
<FirstName Initial="A" Totaldigits="six" Lastletter="A"/>
</Employee>
</Company>
Since values of Initial
and Totaldigits
don't change, I get their values.
I am looking to get the values of all Lastletter
attributes (so 'T','Y', 'A')
Using this in C#, in FirstName
, I am only getting the first value in Lastletter
which is "T",
string digit = root.Attribute("Lastletter").Value;
What should I change/add to this line to get all of Lastletter
values?
CodePudding user response:
This expression loops on all the elements named Employee then iterates its child elements named FirstName and applies an expression that:
- Ensures element has an
Attribute
named Lastletter - If so, dereferences its
Value
property
static void Main(string[] args)
{
var root = XElement.Parse(source);
foreach (var employee in root.Elements("Employee"))
{
var lastLetters =
employee.Elements("FirstName")
.Where(match => match.Attribute("Lastletter") != null)
.Select(match=>match.Attribute("Lastletter").Value);
Console.WriteLine($"Last Letters: {string.Join(",", lastLetters)}");
}
}
const string source =
@"<Company>
<Employee>
<FirstName Initial=""A"" Totaldigits=""six"" Lastletter=""T""/>
<FirstName Initial=""A"" Totaldigits=""six"" Lastletter=""Y""/>
<FirstName Initial=""A"" Totaldigits=""six"" Lastletter=""A""/>
</Employee>
</Company>";
If the goal is to have a one-liner, you could try this:
static void Main(string[] args)
{
var root = XElement.Parse(source);
String[] results =
root
.Elements("Employee")
.Select(employee =>
string.Join(
",",
employee.Elements("FirstName")
.Where(match => match.Attribute("Lastletter") != null)
.Select(match => match.Attribute("Lastletter").Value)
)
)
.ToArray();
foreach (var result in results)
{
Console.WriteLine($"Last Letters: {result}");
}
}
const string source =
@"<Company>
<Employee>
<FirstName Initial=""A"" Totaldigits=""six"" Lastletter=""T""/>
<FirstName Initial=""A"" Totaldigits=""six"" Lastletter=""Y""/>
<FirstName Initial=""A"" Totaldigits=""six"" Lastletter=""A""/>
</Employee>
<Employee>
<FirstName Initial=""B"" Totaldigits=""six"" Lastletter=""I""/>
<FirstName Initial=""B"" Totaldigits=""six"" Lastletter=""D""/>
<FirstName Initial=""B"" Totaldigits=""six"" Lastletter=""K""/>
</Employee>
</Company>";