2012-11-20 40 views
1

我想從XML文件添加字符串到文本框,但沒有成功yet.What我想要做的是通過「日期」元素,如果「bejovo」與「date」元素匹配,則將元素「name」的值放入List中,然後將價格相加。這裏是我的代碼。如果條件爲真,從xml中添加指定的元素到文本框

if (File.Exists(path)) 
      { 
       XDocument doc = XDocument.Load(path); 
       var c = from x in doc.Descendants("order") 
         where x.Element("date").Value == bejovo 
         select new 
         { 
          //?? 
         }; 
       foreach (var item in c) 
       { 
        textBox1.Text = item.ToString();      
       } 
      } 

這裏是我的XML文件:「二零一二年十一月二十零日1時29分二十○秒」

<user id="0"> 
    <order id="0"> 
     <date>2012.11.20. 1:29:20</date> 
     <menuelem db="0"> 
     <name>Pizza</name> 
     <price>1290</price> 
     </menuelem> 
     <menuelem db="1"> 
     <name>Coke</name> 
     <price>300</price> 
     </menuelem> 
    </order> 
    </user> 
<user id="0"> 
    <order id="1"> 
     <date>2012.11.19. 21:49:29</date> 
     <menuelem db="0"> 
     <name>Milk</name> 
     <price>200</price> 
     </menuelem> 
    </order> 
    </user> 

所以,如果bejovo =,那麼我的結果必然是「比薩」和「可樂」而且價格是1590

回答

0

當然這個代碼有沒有驗證:

XDocument doc = XDocument.Load("In.xml"); 
var c = from x in doc.Descendants("order") 
     where x.Element("date").Value == "2012.11.20. 1:29:20" 
     select new 
     { 
      Names = string.Join(", ", x.Elements("menuelem") 
             .Elements("name") 
             .Select(s => s.Value)), 
      Price = x.Elements("menuelem") 
        .Elements("price") 
        .Select(s => decimal.Parse(s.Value)) 
        .Sum() 
     }; 
foreach (var item in c) 
{ 
    textBox1.Text = string.Format("{0}\tprice:{1}", item.Names, item.Price); 
} 

輸出是這樣:Pizza, Coke price:1590

0

可能會嘗試沿着這些路線。下面的代碼未經測試,目前無法在Visual Studio中加載和測試。

var items = doc 
    .Elements("user") 
    .Elements("order") 
    .Where(o => (string)o.Element("date") == bejovo) 
    .Elements("menuelem") 
    .Select(m => new 
    { 
    Name = (string)m.Element("name"), 
    Price = (int?).Element("price") 
    }; 
var names = items.Select(i => i.Name).ToList(); 
var price = items.Select(i => i.Price).Sum();