2010-08-23 112 views
1

我有两个xml文件。LINQ to XML查询

首先company.xml:

<company active="1"> 
    <name>name1</name> 
    <location>first floor</location> 
    <room>25</room> 
    <category>power,gas,water</category> 
</company> 

<company active="1"> 
    <name>name2</name> 
    <location>second floor</location> 
    <room>23</room> 
    <category>water,gas</category> 
</company> 

二bills.xml:

<bill> 
    <name>bill1</name> 
    <category>power</category> 
    <total>5432</total> 
</bill> 

<bill> 
    <name>bill2</name> 
    <category>power</category> 
    <total>1200</total> 
</bill> 

<bill> 
    <name>bill2</name> 
    <category>gas</category> 
    <total>3464</total> 
</bill> 

现在我有这个疑问在那里我被companyname元素分组XML以及从bills合计总价值

XDocument fDoc = XDocument.Load("company.xml"); 
XDocument rDoc = XDocument.Load("bills.xml"); 


var query = from f in fDoc.Elements("company") 
where ((string)f.Attribute("active")).Equals("1") 
orderby f.Element("name").Value 
from r in racuniRoot.Elements("bill") 
where (f.Element("category").Value).Split(',').Contains(r.Element("category").Value) 
group new 
{ 
BillTotal = Convert.ToInt32(r.Element("total").Value) 
} 
by f.Element("name").Value into g 
select new 
{ 
Name = g.Key, 
Total = g.Sum(rec =>rec.BillTotal) 
}; 

foreach (var k in query) 
{ 
    litList.Text += k.Name + k.Total; 
} 

所以结果与thi的查询是:

名1 6632

名2 3464

这是好的,但如何选择在此查询其他company元素(locationroom)?

这就是我想要的最终结果:

名1 6632一楼25

名23464秒楼23

我怎样才能做到这一点?

谢谢!

回答

0

通过名称,位置和房间做一组

var query = from f in fDoc.Descendants("company") 
        where ((string)f.Attribute("active")).Equals("1") 
        orderby f.Element("name").Value 
        from r in rDoc.Descendants("bill") 
        where (f.Element("category").Value).Split(',').Contains(r.Element("category").Value) 
        group new 
        { 
         BillTotal = Convert.ToInt32(r.Element("total").Value) 
        } 
        by f.Element("name").Value + f.Element("location").Value + f.Element("room").Value into g 
        select new 
        { 
         Name = g.Key, 
         Total = g.Sum(rec => rec.BillTotal), 
        };