Linq/XML: grouping results properly within XML element

风流意气都作罢 提交于 2019-12-11 15:45:46

问题


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

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);

The output is of the form:

<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>

instead of:

<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?


回答1:


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.



来源:https://stackoverflow.com/questions/1328082/linq-xml-grouping-results-properly-within-xml-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!