0

I have following xml structure:

 //this is the root
<factory ver="123" id="1">
    //can be a lot of lines
   <line id="123" name="line name">
         //can be alot of machines
         <machine id="101" Type="Weel">
           <setting Title="Filled" Value="No"  />
           <setting Title="Size"   Value="14" />
           <setting Title="Mandatory" Value="No"/>
        </machine>
        <machine id="222" Type="Reel">
           <setting Title="Filled" Value="No"  />
           <setting Title="Size"   Value="14" />
           <setting Title="Mandatory" Value="No"/>
        </machine>
   </line>
  <line id="312" name="line name1">
         <machine id="111" Type="Weel">
           <setting Title="Filled" Value="No"  />
           <setting Title="Size"   Value="14" />
           <setting Title="Mandatory" Value="No"/>
        </machine>
        <machine id="333" Type="Reel">
           <setting Title="Filled" Value="No"  />
           <setting Title="Size"   Value="14" />
           <setting Title="Mandatory" Value="No"/>
        </machine>

How I can via Linq and XDocument by given machine ID to get it's type and all it's settings(there can be much more not listed all of them).

2 Answers 2

3

Well, you can get to a particular machine easily like this:

var element = doc.Descendants("machine")
                 .FirstOrDefault(x => (int) x.Attribute("id") == targetId);

That will return null if there are no matching elements.

If you want to go from that to a dictionary of setting name to setting value, you can use:

// After checking whether `element` is null of course
var settings = element.Elements("setting")
                      .ToDictionary(x => x.Attribute("Title").Value,
                                    x => x.Attribute("Value").Value);

And the type is simple:

var type = (string) element.Attribute("Type");
Sign up to request clarification or add additional context in comments.

Comments

0

Like this:

XElement.Parse(...).Descendants("machine").First(m => m.Attribute("id").Value == x)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.