2011-09-05 74 views
0

一个XML文件,我有以下XML结构:解析与LINQ

//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> 

我怎样才能通过LinqXDocument通过给定的机器ID来获得它的类型和它所有的设置(可以有更没有列出所有这些)。

回答

3

那么,你可以得到一个特定的机器上方便地像这样:

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

,将返回null如果没有匹配的元素。

如果你想从去设定名称设定值的字典,你可以使用:

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

而且类型很简单:

var type = (string) element.Attribute("Type"); 
0

像这样:

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