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).
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");
Like this:
XElement.Parse(...).Descendants("machine").First(m => m.Attribute("id").Value == x)
精彩评论