XML to LinQ - General questions

  • Thread starter Thread starter Markus Freitag
  • Start date Start date
M

Markus Freitag

Guest
Hello,
How can I create a query and make sure if the element does not exist, an exception is thrown?
With
resultPosition?.Element
is not working.
I must check it this way.

if (resultPosition.Element("PROCESS") == null)
continue;
// ------------------------------------
Which spelling is better? What are they called? Isn't both LinQ?
var resultProcessStep2 = (from x in resultPosition?.Element("PROCESS")
//or
var resultProcessStep = resultPosition?.Element("PROCESS")?.Elements()
// ------------------------------------
How can I get the next element and output the name? NextElement does not exist.
xeStep.HasElements
Is perhaps a variant faster?
// -------------------------------------
FirstOrDefault() --> can be null
First() --> if null get an exception, right?
Select.Single()
My XML and my coding. Work well now.
<SIDE1>
<POSITIONS>
<POSITION>
<NUMBER value="1" />
<ACTIVE value="1" />
<PROCESS>
<STEP value="GROUP_RECEIVER">
<COLOR1 value="green" />
<COLOR2 value="red" />
</STEP>
<STEP value="GROUP_RADAR">

....
<SIDE2>
...
<SIDE3>

for (int side = 1; side <= 3; side++)
{
var resultPositions = xDocProgramID.Element("ROOT").
Element("PROGRAM").
Element($"SIDE{side}").Element("POSITIONS")?.Elements();

foreach (var resultPosition in resultPositions)
{
if (resultPosition.Element("PROCESS") == null)
continue;

var resultProcessStep2 = (from x in resultPosition?.
Element("PROCESS")?.
Elements()
where x?.Name?.LocalName == "STEP" && x.Attribute("value")?.
Value.ToLower() == "group_receiver"
select x).ToList();
var resultProcessStep = resultPosition?.
Element("PROCESS")?.Elements().
Where(x => x.Name?.LocalName == "STEP" &&
x.Attribute("value")?.Value.ToLower() == "markposition").ToList();

foreach (XElement xeStep in resultProcessStep.Elements())
{
//XElement xeCheckIt = (XElement) xeStep.NextNode;
switch (xeStep?.Name.LocalName)
{
case "COLOR1":
xeStep.SetAttributeValue
("value", newColor1);

Many thanks for tips and your help in advance.
Many greetings
Markus

Continue reading...
 
Back
Top