Linq/XML:在XML元素内正确分组结果 [英] Linq/XML: grouping results properly within XML element

查看:80
本文介绍了Linq/XML:在XML元素内正确分组结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我询问如何以XML格式返回Linq查询结果,并且得到了答案

OK, I asked for how to return a Linq query results as XML, and I got the answer here.

但是有一个小问题:结果不会在XML内进行逻辑分组.例如:

But there's one little problem: the results do not get grouped logically within the XML. For example:

XElement xml = new XElement("States",
  from s in MyStates
  from cy in s.Counties
  from c in cy.Cities
  where s.Code == "NY"
  orderby s.Code, cy.Name, c.Name
  select new XElement("State",
    new XAttribute("Code", s.Code),
    new XAttribute("Name", s.Name),
    new XElement("County",
      new XAttribute("Name", cy.Name),
      new XElement("City",
        new XAttribute("Name", c.Name)
      )
    )
  )
);

Console.WriteLine(xml);

输出的形式为:

<State Code="NY" Name="New York ">
  <County Name="WYOMING">
    <City Name="WARSAW" />
  </County>
</State>
<State Code="NY" Name="New York ">
  <County Name="WYOMING">
    <City Name="WYOMING" />
  </County>
</State>
<State Code="NY" Name="New York ">
  <County Name="YATES">
    <City Name="BELLONA" />
  </County>
</State>
<State Code="NY" Name="New York ">
  <County Name="YATES">
    <City Name="MIDDLESEX" />
  </County>
</State>
<State Code="NY" Name="New York ">
  <County Name="YATES">
    <City Name="PENN YAN" />
  </County>
</State>
<State Code="NY" Name="New York ">
  <County Name="YATES">
    <City Name="RUSHVILLE" />
  </County>
</State>

代替:

<State Code="NY" Name="New York ">
  <County Name="WYOMING">
    <City Name="WARSAW" />
    <City Name="WYOMING" />
  </County>
  <County Name="YATES">
    <City Name="BELLONA" />
    <City Name="MIDDLESEX" />
    <City Name="PENN YAN" />
    <City Name="RUSHVILLE" />
  </County>
</State>

如何使结果按预期显示?

How do I get the results to appear as desired?

推荐答案

要获得所需的结果,我相信您必须将LINQ嵌套到XML查询中.在外部查询中,您必须查询不同的州...然后是内部查询以获取该州的县...然后是另一个内部查询以获取该县的城市.

To get the results you want, I believe you'll have to nest LINQ to XML queries. On the outer query, you'll have to query for distinct states...then an inner query to get the counties for that state...then another inner query to get the cities for that county.

这篇关于Linq/XML:在XML元素内正确分组结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆