2011-09-15 15 views
1

私はリストボックスに注文のすべての要素をポーズしようとしています。リストボックスは、要素ではなくコレクションを追加するだけです。助けてください!Linq to XML using ASP.Net

XDocument doc = XDocument.Load(Server.MapPath("App_Data/Orders.xml")); 

     string order = ddl.SelectedValue; 

     var results = doc.Descendants("Order").Where(o => o.Attribute("OrderNumber").Value == "SO43659") 
         .Select(o => o.Elements("LineItem")); 

     foreach (var r in results) 
     { 
      ListBox1.Items.Add(new ListItem(r.ToString())); 

     } 

XMLフラグメント:あなたはvarを使用しなかった場合

<Order OrderNumber="SO43659"> 
    <LineItem Line="1" PID="349" Qty="1" Price="2024.9940" Freight="50.6249" /> 
    <LineItem Line="2" PID="350" Qty="3" Price="2024.9940" Freight="151.8746" /> 
    <LineItem Line="3" PID="351" Qty="1" Price="2024.9940" Freight="50.6249" /> 
    <LineItem Line="4" PID="344" Qty="1" Price="2039.9940" Freight="50.9999" /> 
    <LineItem Line="5" PID="345" Qty="1" Price="2039.9940" Freight="50.9999" /> 
    <LineItem Line="6" PID="346" Qty="2" Price="2039.9940" Freight="101.9997" /> 
    <LineItem Line="7" PID="347" Qty="1" Price="2039.9940" Freight="50.9999" /> 
    <LineItem Line="8" PID="229" Qty="3" Price="28.8404" Freight="2.1630" /> 
    <LineItem Line="9" PID="235" Qty="1" Price="28.8404" Freight="0.7210" /> 
    <LineItem Line="10" PID="218" Qty="6" Price="5.7000" Freight="0.8550" /> 
    <LineItem Line="11" PID="223" Qty="2" Price="5.1865" Freight="0.2593" /> 
    <LineItem Line="12" PID="220" Qty="4" Price="20.1865" Freight="2.0187" /> 
    </Order> 
+0

をあなたは、ドロップダウンにするLineItemのいずれかのparticulat属性を表示するには、正確に何をしようとしていますか? –

答えて

2
var results = doc.Descendants("Order") 
       .Where(o => o.Attribute("OrderNumber").Value == "SO43659") 
       .FirstOrDefault(); 

foreach (var r in results.Elements("LineItem")) 
{ 
    ListBox1.Items.Add(new ListItem(r.ToString())); 
} 
1

、あなたは間違っているか見たい - resultsの各要素は、要素のシーケンスです。ここにあなたのコードはvarなしだ:

IEnumerable<IEnumerable<XElement>> results = 
    doc.Descendants("Order") 
     .Where(o => o.Attribute("OrderNumber").Value == "SO43659") 
     .Select(o => o.Elements("LineItem")); 

foreach (IEnumerable<XElement> r in results) 
{ 
    ListBox1.Items.Add(new ListItem(r.ToString())); 

} 

私はそれはあなたが後にしているものではありません疑います。あなたが代わりにこれを使用することができます:

// Will go bang if there isn't exactly one matching order 
IEnumerable<XElement> results = 
    doc.Descendants("Order") 
     .Where(o => o.Attribute("OrderNumber").Value == "SO43659") 
     .Single() 
     .Select(o => o.Elements("LineItem")); 

または:

// Will find *all* the LineItem elements under *all* matching orders 
IEnumerable<XElement> results = 
    doc.Descendants("Order") 
     .Where(o => o.Attribute("OrderNumber").Value == "SO43659") 
     .SelectMany(o => o.Elements("LineItem"));