2010-03-22 43 views
5

Tôi đang gặp sự cố khi truy vấn LINQ hoạt động. Tôi có XML này:LINQ to truy vấn lồng nhau XML

<devices> 
    <device id ="2142" name="data-switch-01"> 
    <interface id ="2148" description ="Po1"/> 
    </device> 
    <device id ="2302" name="data-switch-02"> 
    <interface id ="2354" description ="Po1"/> 
    <interface id ="2348" description ="Gi0/44" /> 
    </device> 
</devices> 

Và mã này:

var devices = from device in myXML.Descendants("device") 
       select new 
       { 
        ID = device.Attribute("id").Value, 
        Name = device.Attribute("name").Value, 
       }; 

foreach (var device in devices) 
{ 
    Device d = new Device(Convert.ToInt32(device.ID), device.Name); 

    var vIfs = from vIf in myXML.Descendants("device") 
        where Convert.ToInt32(vIf.Attribute("id").Value) == d.Id 
        select new 
        { 
         ID = vIf.Element("interface").Attribute("id").Value, 
         Description = vIf.Element("interface").Attribute("description").Value, 
        }; 
    foreach (var vIf in vIfs) 
    { 
     DeviceInterface di = new DeviceInterface(Convert.ToInt32(vIf.ID), vIf.Description); 
     d.Interfaces.Add(di); 
    } 

    lsDevices.Add(d); 
} 

đối tượng Device My chứa một danh sách của DeviceInterfaces mà tôi cần phải cư từ XML. Hiện tại, mã của tôi chỉ điền vào giao diện đầu tiên, mọi mã tiếp theo bị bỏ qua và tôi không thể hiểu tại sao.

Tôi cũng đánh giá cao bất kỳ nhận xét nào về việc đây có phải là cách phù hợp để thực hiện hay không. Các vòng foreach lồng nhau có vẻ hơi lộn xộn với tôi

Cheers

Trả lời

12
IEnumerable<Device> devices = 
    from device in myXML.Descendants("device") 
    select new Device(device.Attribute("id").Value, device.Attribute("name").Value) 
    { 
    Interfaces = (from interface in device.Elements("Interface") 
        select new DeviceInterface(
         interface.Attribute("id").Value, 
         interface.Attribute("description").Value) 
       ).ToList() //or Array as you prefer 
    } 

Điểm cơ bản ở đây là bạn làm một loại "subselect" trên thiết bị (mà là một Descendant), tìm kiếm tất cả các Interface yếu tố nó chứa.

Tạo mới DeviceInterface cho mỗi "giao diện" trong từng thiết bị.

+0

Nhờ đó trông đẹp hơn nhiều, tôi sẽ cung cấp cho nó sau một shot :) – user299342

+0

Yep đó là vị trí trên, cheers! – user299342

1

Nhanh chóng và bẩn

var query = from device in document.Descendants("device") 
      select new 
      { 
       ID = device.Attribute("id").Value, 
       Name = device.Attribute("name").Value, 
       Interfaces = from deviceInterface in device.Descendants("interface") 
          select new 
          { 
           ID = deviceInterface.Attribute("id").Value, 
           Description = deviceInterface.Attribute("description") 
          } 
      }; 
+0

Bạn vẫn cần phải lặp qua 'truy vấn' để tạo (hoặc điền) một' Danh sách '(xem' lsDevices' trong mã đã đăng). –

Các vấn đề liên quan