好的,我问过如何将Linq查询结果作为XML返回,我得到了答案here。
但是有一个小问题:结果不会在XML中逻辑分组。例如:
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>
如何根据需要显示结果?
答案 0 :(得分:1)
为了获得您想要的结果,我相信您必须将LINQ嵌套到XML查询中。在外部查询中,您将必须查询不同的状态...然后是内部查询以获取该状态的县...然后是另一个内部查询来获取该县的城市。