我有以下需要转换为其他形式的 xml。我有一个 C# 代码可以做到这一点,但它有一个很难跟踪的错误。我相信 Linq 可以提供一种更容易出错的方法来做到这一点。输入xml:
<NewDataSet>
  <Table>
    <RoleId>5</RoleId>
    <Code>DP</Code>
    <Description>Process data</Description>
    <Task>Validate indices</Task>
    <TaskId>12</TaskId>
    <Country>BE</Country>
    <CountryId>3</CountryId>
  </Table>
  <Table>
    <RoleId>5</RoleId>
    <Code>DP</Code>
    <Description>Process data</Description>
    <Task>calculate indices</Task>
    <TaskId>11</TaskId>
    <Country>US</Country>
    <CountryId>4</CountryId>
  </Table>
  <Table>
    <RoleId>5</RoleId>
    <Code>DP</Code>
    <Description>Process data</Description>
    <Task>Calculate indices</Task>
    <TaskId>11</TaskId>
    <Country>UK</Country>
    <CountryId>5</CountryId>
  </Table>
  <Table>
    <RoleId>1</RoleId>
    <Code>DR</Code>
    <Description>View data</Description>
    <Task>View Reports</Task>
    <TaskId>9</TaskId>
    <Country>SC</Country>
    <CountryId>17</CountryId>
  </Table>
  <Table>
    <RoleId>1</RoleId>
    <Code>DR</Code>
    <Description>View data</Description>
    <Task>View Basics</Task>
    <TaskId>10</TaskId>
    <Country>SC</Country>
    <CountryId>17</CountryId>
  </Table>
  <Table>
    <RoleId>1</RoleId>
    <Code>DR</Code>
    <Description>View data</Description>
    <Task>Download data</Task>
    <TaskId>11</TaskId>
    <Country>FR</Country>
    <CountryId>15</CountryId>
  </Table>
</NewDataSet>
我需要的输出如下:
<NewDataSet>
 <Table>
    <RoleId>5</RoleId>
    <Code>DP</Code>
    <Description>Process data</Description>
    <Task>Validate indices,Calculate indices,</Task>
    <TaskId>12,11</TaskId>
    <Country>BE,US,UK</Country>
    <CountryId>3,4,5</CountryId>
  </Table>
  <Table>
    <RoleId>1</RoleId>
    <Code>DR</Code>
    <Description>Process data from commercial fisheries</Description>
    <Task>View Reports,View Basics,View data</Task>
    <TaskId>9,10,11</TaskId>
    <Country>SC,FR</Country>
    <CountryId>17,15</CountryId>
  </Table>
</NewDataSet>
如您所见,元素按 RoleId、Code 和 Description 分组。
我创建了一个 custum 对象来将 xml 元素投影到
public class Table
{
   public int RoleId {get;set;}
   public string Code  {get;set;}
   public string  Description {get;set;}
   public string Task {get;set;}
   public int TaskId {get;set;}
   public string  Country {get;set;}
   public int CountryId  {get;set;}
}
然后的想法是使用这个 custum 对象列表来重新创建一个 xml 文档。但我在想可能有更直接的方式。无需使用自定义对象列表。
元素的其余部分被简单地连接起来。我希望有人对如何使用 Linq to XML 实现这一点有一个想法。提前谢谢了