Reputation: 27
i read about Linq and xml, but i dont know if i do it the right way...
here my XML Configuration File:
<?xml version="1.0" encoding="utf-8"?>
<Configuration>
<Priorities>
<Priority Index="0">Zero</Priority>
<Priority Index="1">One</Priority>
<Priority Index="2">Two</Priority>
<Settings>
<Name>PriorityName</Name>
<DisplayName>PriorityDisplayName</DisplayName>
<Active>true</Active>
<Index>0</Index>
</Settings>
</Priorities>
<Workcenters>
<Workcenter Index="0">TEAM_0</Workcenter>
<Workcenter Index="1">TEAM_1</Workcenter>
<Workcenter Index="2">TEAM_2</Workcenter>
<Settings>
<Name>WorkcentersName</Name>
<DisplayName>WorkcentersDisplayName</DisplayName>
<Active>false</Active>
<Index>1</Index>
</Settings>
</Workcenters>
<ErrorPages>
<ErrorPage>
<Name>Error_1</Name>
<Type>Critical</Type>
</ErrorPage>
<ErrorPage>
<Name>Error_2</Name>
<Type>Normal</Type>
</ErrorPage>
</ErrorPages>
</Configuration>
Now i access all Priorities like this:
//Get Prios
XElement xelement = XElement.Load(xmlPath2);
IEnumerable<XElement> priorities = xelement.Descendants("Priorities");
var prios = priorities.Elements("Priority").ToList();
var settings = priorities.Elements("Settings");
foreach (XElement priority in prios)
{
Console.WriteLine(priority.Attribute("Index").Value);
Console.WriteLine(priority.Value);
}
foreach (XElement setting in settings)
{
Console.WriteLine(setting.Element("Name").Value);
Console.WriteLine(setting.Element("Active").Value);
Console.WriteLine(setting.Element("Index").Value);
Console.WriteLine(setting.Element("DisplayName").Value);
}
is this the right way to access the Elements? i think there will be a better to read solution.
Can u help me?
thanks
Upvotes: 0
Views: 27
Reputation: 406
You could use XPathSelectElements extension method.
So your code would look something like:
XElement xelement = XElement.Load(xmlPath2);
foreach (XElement priority in xelement.XPathSelectElements("Priorities/Priority"))
{
Console.WriteLine(priority.Attribute("Index").Value);
Console.WriteLine(priority.Value);
}
foreach (XElement setting in xelement.XPathSelectElements("Priorities/Settings"))
{
Console.WriteLine(setting.Element("Name").Value);
Console.WriteLine(setting.Element("Active").Value);
Console.WriteLine(setting.Element("Index").Value);
Console.WriteLine(setting.Element("DisplayName").Value);
}
Upvotes: 1